Insertion Sort

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

Insertion Sort

1 <?php 2 function swap(&$a, &$b){ 3 $c = $a; 4 $a = $b; 5 $b = $c; 6 } 7 8 # insertion sort 9 # ascend10 function sortInsertion(&$a){ # a is an array of numbers11 12 # length of a13 $m = count($a);14 15 if($m < 2){16 return;17 }18 19 # for m numbers, we have m-1 numbers to insert20 for($i=1; $i<=$m-1; $i++){21 for($j=$i; $j>0; $j--){22 if($a[$j] < $a[$j-1]){23 swap($a[$j], $a[$j-1]);24 }25 }26 }27 28 return;29 }30 31 $arr = range(5, 0);32 sortInsertion($arr);33 echo implode(', ', $arr);34 35 // 0, 1, 2, 3, 4, 536 ?>

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