php的插入算法

 1 <?php
 2 /**
 3 * 插入排序
 4 */
 5 class insterSort 
 6 {
 7     public function sort_out($sortNum){
 8         $length=count($sortNum);//计算数组长度
 9         for ($i=0; $i <$length ; $i++) { 
10             $temp=$sortNum[$i];//取出插入值
11             for ($j=$i-1; $j>=0; $j--) { //要注意这里是大于等于零,这里数组的下标是从0开始的
12                 if($temp<$sortNum[$j]){//对数组中元素位置进行替换
13                     $sortNum[$j+1]=$sortNum[$j];
14                     $sortNum[$j]=$temp;
15                 }
16                 else{
17                     break;
18                 }
19             }
20         }
21         return $sortNum;
22     }
23 
24 }
25 $insterSort=new insterSort();//将插入排序类实例化
26 $arr=["5","2","9","4","1"];//定义一个测试的数组
27 $res=$insterSort->sort_out($arr);//对测试数组进行排序
28 print_r($res);//输出排序后的结果
原文地址:https://www.cnblogs.com/luosong3/p/10557523.html