Selection Sort

王朝学院·作者佚名  2016-05-25
窄屏简体版  字體: 小  |  中  |  大  |  超大  

Selection SortRed 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 ?>

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航