码迷,mamicode.com
首页 > 其他好文 > 详细

Insertion Sort

时间:2014-11-09 17:55:55      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   sp   for   div   

bubuko.com,布布扣

Implementation in PHP:

 1 <?php
 2 /* insertion sort:
 3     1. operate directly on input array (&), not on a copy
 4     2. sort as ascend
 5 
 6     a is input array
 7     m is length of a
 8     i/j/k is for-loop counter
 9     t is temp value
10 */
11 function sortInsertion(&$a){
12     $m = count($a);
13     $n = $m - 1;
14     $sub;
15     for($i=1; $i<$m; $i++){
16         $t = $a[$i];
17         $sub = $i;
18         for($j=0; $j<$i; $j++){
19             if($t < $a[$j]){
20                 $sub = $j;
21              break;
22             }
23             else{
24                 // do nothing
25             }
26         }
27         for($k=$i; $k>$sub; $k--){
28             $a[$k] = $a[$k-1];
29         }
30         $a[$sub] = $t;
31     }
32 }
33 
34 $arr = array(9, 5, 2, 7, 3);
35 sortInsertion($arr);
36 echo implode(‘, ‘, $arr);
37 
38 // 2, 3, 5, 7, 9
39 ?>

 

Insertion Sort

标签:style   blog   http   io   color   ar   sp   for   div   

原文地址:http://www.cnblogs.com/crepesofwrath/p/4085602.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!