·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> php网站开发 >> Selection Sort

Selection Sort

作者:佚名      php网站开发编辑:admin      更新时间:2022-07-23
Selection Sort

selection sort wikipediaRed is current min. Yellow is sorted list. Blue is current item.

 1 <?php 2 function swap(&$a, &$b){ 3     $c = $a; 4     $a = $b; 5     $b = $c; 6 } 7  8 # selection sort 9 # ascend10 function sortSelection(&$a){ # a is an array of numbers11 12     # length of a13     $m = count($a);14 15     if($m < 2){16         return;17     }18 19     # index of min; remains null if rest of the numbers ascending20     $sub = null;21 22     # for m numbers, we have m-1 mins to find and put on the left23     for($i=1; $i<=$m-1; $i++){24 25         # i=1, a min in m numbers to find               ; 0, m-126         # i=2, a min in m-1 numbers on the right to find; 1, m-127         # i=3, a min in m-2 numbers on the right to find; 2, m-1; i-1, m-128         for($j=$i-1; $j<$m-1; $j++){29 30             # if this > never happens, it means an ascending array already31             if($a[$j] > $a[$j+1]){32                 $sub = $j+1;33             }34         }35 36         if($sub === null){37             break;38         }39         else{40             swap($a[$i-1], $a[$sub]);41             $sub = null;42         }43     }44 45     return;46 }47 48 $arr = range(5, 0);49 sortSelection($arr);50 echo implode(', ', $arr);51 52 // 0, 1, 2, 3, 4, 553 ?>