/*选择排序*/
$arr = [14,18,19,37,23,40,29,30,11,7,2,1,8,6,3,5,4,5,4] ;
$sorted_arr = selectSort($arr,0);
myPrint($sorted_arr); // 1 2 3 4 4 5 5 6 7 8 11 14 18 19 23 29 30 37 40 [Finished in 0.1s]
function selectSort($arr,$start)
{
$min = $start;
for ($i=$start+1; $i <count($arr) ; $i++) {
if($arr[$i]<$arr[$min])$min = $i;
}
swap($arr,$start,$min);
$start++;
if($start==count($arr)-1)return $arr;
else return selectSort($arr,$start);
}
/*自定义格式数组输出*/
function myPrint($arr){
foreach ($arr as $value) {
echo $value." " ;
}
echo "\n";
}
/*交换索引指向的元素*/
function swap(&$arr,$i,$j){
if($i==$j)return;
$tmp =$arr[$j];
$arr[$j] =$arr[$i];
$arr[$i] =$tmp;
}
网友评论