Home > Backend Development > PHP Tutorial > PHP implementation of selection sorting ideas and code

PHP implementation of selection sorting ideas and code

不言
Release: 2023-04-04 12:36:01
forward
2921 people have browsed it

This article brings you the code for implementing selection sorting in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Selection sorting:

1. The array is divided into two parts, the front part is sorted, and the latter part is unordered
2. Two-level loop, first assume The first index of the current loop is the minimum value. The inner loop looks for a value smaller than this index and finds the exchange

for i;i<len;i++
    minIndex=i
    for j=i+1;j<len;j++
        if arr[j]<arr[minIndex]
            minIndex=j
    t=arr[i]
    arr[i]=arr[minIndex]
    arr[minIndex]=arr[i]
Copy after login

<?php
function selectSort(&$arr){
        $len=count($arr);
        for($i=0;$i<$len;$i++){
                $minIndex=$i;//假定当前i是最小值
                for($j=$i+1;$j<$len;$j++){
                        if($arr[$j]<$arr[$minIndex]){
                                $minIndex=$j;
                                break;
                        }   
                }   
                $t=$arr[$i];
                $arr[$i]=$arr[$minIndex];
                $arr[$minIndex]=$t;
        }   
        return $arr;
}

$arr=array(2,3,1,4,9,5);
selectSort($arr);
var_dump($arr);
Copy after login

The above is the detailed content of PHP implementation of selection sorting ideas and code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template