首页 > 代码库 > Insertion Sort

Insertion Sort

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 value10 */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 nothing25             }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, 939 ?>

 

Insertion Sort