当前位置:Gxlcms > PHP教程 > InsertionSort,insertionsort_PHP教程

InsertionSort,insertionsort_PHP教程

时间:2021-07-01 10:21:17 帮助过:21人阅读

Insertion Sort,insertionsort


insertion sort wikipedia

 1 php
 2 function swap(&$a, &$b){
 3     $c = $a;
 4     $a = $b;
 5     $b = $c;
 6 }
 7 
 8 # insertion sort
 9 # ascend
10 function sortInsertion(&$a){ # a is an array of numbers
11 
12     # length of a
13     $m = count($a);
14 
15     if($m < 2){
16         return;
17     }
18 
19     # for m numbers, we have m-1 numbers to insert
20     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, 5
36 ?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/908459.htmlTechArticleInsertion Sort,insertionsort 1 ? php 2 function swap( $a , $b ){ 3 $c = $a ; 4 $a = $b ; 5 $b = $c ; 6 } 7 8 # insertion sort 9 # ascend 10 function sortInsertion( $a ){ # a is a...

人气教程排行