Home > Article > Backend Development > PHP implementation of selection sorting ideas and code
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]
<?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);
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!