Insert Sort principle: Enter an element, examine each element in the array list, insert it into an appropriate position in an already sequenced sequence, and keep the sequence in order, and the array is sorted when the last element is placed in the appropriate position.
PHP Implementation Method 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 Implementation Method 2:
1 functionInsert$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){Ten $array[$j+1]=$array[$j]; One}Else{ A Break; - } - } the $array[$j+1]=$temp; - } - return $array; -}
PHP Implementation 3:
1 functionInsert$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){Ten $array[$j+1]=$array[$j]; One $j=$j-1; A } - $array[$j+1]=$temp; - the } - return $array; -}
PHP implementation four:
1 functionInsert$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){Ten $array[$j+1]=$array[$j]; One $array[$j]=$temp; A $j=$j-1; - } - } the return $array; -}
Want to be helpful to everyone, have time to use C implementation under the insertion sort code.
PHP Implementation Insert Sort