导航

选择排序

Posted on 2020-11-09 19:32  玻璃星  阅读(55)  评论(0编辑  收藏  举报
<?php
function selection_sort(&$arr){
    $count = count($arr);
    for($i=0;$i<$count-1;$i++){
        $temp = $i;
        for($j=$i+1;$j<$count;$j++){
            if($arr[$j]<$arr[$temp]){
               $temp = $j;
            }
        }
        if($temp != $i){
            $arr[$i] = $arr[$temp]^$arr[$i];    //下面注释里的$arr[$i],$arr[$temp]是交换前的
            $arr[$temp] = $arr[$i]^$arr[$temp]; // $arr[$temp]^$arr[$i]^$arr[$temp]
            $arr[$i] =$arr[$temp]^$arr[$i];    // $arr[$temp]^$arr[$i]^$arr[$temp]^$arr[$temp]^$arr[$i]
        }
    }
}

$arr = [5,4,3,2,1,9,8,7,6];
selection_sort($arr);
echo '<pre/>';
print_r($arr);

//结果
//Array
//(
//    [0] => 1
//    [1] => 2
//    [2] => 3
//    [3] => 4
//    [4] => 5
//    [5] => 6
//    [6] => 7
//    [7] => 8
//    [8] => 9
//)