标签:
插入排序原理:输入一个元素,检查数组列表中的每个元素,将其插入到一个已经排好序的数列中的适当位置,使数列依然有序,当最后一个元素放入合适位置时,该数组排序完毕。
php实现方法1:
function insert($array){
$count=count($array);
if($count<=1){
return $array;
}
for($i=1;$i<$count;$i++){
$temp=$array[$i];
for($j=$i-1;$j>=0;$j--){
if($array[$j]>$temp){
$array[$j+1]=$array[$j];
$array[$j]=$temp;
}else{
break;
}
}
}
return $array;
}
php实现方法2:
1 function insert($array){ 2 $count=count($array); 3 if($count<=1){ 4 return $array; 5 } 6 for($i=1;$i<$count;$i++){ 7 $temp=$array[$i]; 8 for($j=$i-1;$j>=0;$j--){ 9 if($array[$j]>$temp){ 10 $array[$j+1]=$array[$j]; 11 }else{ 12 break; 13 } 14 } 15 $array[$j+1]=$temp; 16 } 17 return $array; 18 }
php实现3:
1 function insert($array){ 2 $count=count($array); 3 if($count<=1){ 4 return $array; 5 } 6 for($i=1;$i<$count;$i++){ 7 $temp=$array[$i]; 8 $j=$i-1; 9 while($j>=0&&$array[$j]>$temp){ 10 $array[$j+1]=$array[$j]; 11 $j=$j-1; 12 } 13 $array[$j+1]=$temp; 14 15 } 16 return $array; 17 }
php实现四:
1 function insert($array){ 2 $count=count($array); 3 if($count<=1){ 4 return $array; 5 } 6 for($i=1;$i<$count;$i++){ 7 $temp=$array[$i]; 8 $j=$i-1; 9 while($j>=0&&$array[$j]>$temp){ 10 $array[$j+1]=$array[$j]; 11 $array[$j]=$temp; 12 $j=$j-1; 13 } 14 } 15 return $array; 16 }
希望对大家有帮助,有时间用c实现下插入排序的代码。
标签:
原文地址:http://www.cnblogs.com/hylaz/p/4375148.html