php Select Sort
Published: 2019-04-20

select sort selectionsort

Its working principle is to select the smallest (or largest) element from the data elements to be sorted each time and store it at the beginning of the sequence until all the data elements to be sorted are sorted out.Selection sorting is an unstable sorting method (for example, the sequence [5,5,3] exchanges the first [5] with [3] the first time, causing the first 5 to move behind the second 5).

<?Php

function SelectSort($arr)
{
$count=count($arr);
for ($i=0; $i <$count ;$i++) {
//default $i is the smallest
$min=$i;
for ($j=$i; $j <$count;$j++) {
if ($arr[$min] > $arr[$j]) {
//If the minimum value is greater than the next number, change the value immediately.
$min=$j;
}
}
//Replace the smallest subscript with the first value
if ($min!=$i) {
list($arr[$min],$arr[$i])=[$arr[$i],$arr[$min]];
}
}
return $arr;
}
//Assume the array to be sorted
$arr=array(5,9,8,2,4,6,7,1,25,13,18,22);
$new_arr=SelectSort($arr);
print_r($new_arr);
?>