Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created January 19, 2012 19:38
Show Gist options
  • Select an option

  • Save thinkphp/1642090 to your computer and use it in GitHub Desktop.

Select an option

Save thinkphp/1642090 to your computer and use it in GitHub Desktop.
Insertion Sort in PHP
/**
Insertion Sort in PHP
Twitter : http://twitter.com/thinkphp
Website : http://thinkphp.ro
Google Plus : http://gplus.to/thinkphp
MIT Style License
*/
function insertionSort($arr){
$n = count($arr);
for($i=1;$i<$n;$i++) {
$temp = $arr[$i];
$j = $i - 1;
while($j>=0 && $arr[$j] > $temp) {
$arr[$j+1] = $arr[$j];
$j--;
}
$arr[$j+1] = $temp;
}
return $arr;
}
function insertionSort2($arr){
$n = count($arr);
for($i=1;$i<$n;$i++) {
$temp = $arr[$i];
for($j=$i-1;$j>=0;$j--) {
if($arr[$j] > $temp) {
$arr[$j+1] = $arr[$j];
} else {
break;
}
}
$arr[$j+1] = $temp;
}
return $arr;
}
function insertionSortModified($arr){
$n = count($arr);
for($i=1;$i<$n;$i++) {
$li = 0;
$ls = $i - 1;
$temp = $arr[$i];
while($li<=$ls) {
$m = intval(($li+$ls)/2);
if($temp < $arr[$m]) {
$ls = $m - 1;
} else {
$li = $m + 1;
}
}
for($j=$i-1;$j>=$li;$j--) {
$arr[$j+1] = $arr[$j];
}
$arr[$li] = $temp;
}
return $arr;
}
$arr = array(19,81,20,6,5,4,3,2,1,0);
echo "<h1>Input: ", join($arr,","), "</h1>";
echo "<h1>Output(sorted): ", join(insertionSortModified($arr),","), "</h1>";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment