Skip to content

Instantly share code, notes, and snippets.

@joequery
Created October 12, 2015 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joequery/2433098abe3b6e141492 to your computer and use it in GitHub Desktop.
Save joequery/2433098abe3b6e141492 to your computer and use it in GitHub Desktop.
Recursive PHP Insertion Sort
<?php
function insertion_sort($a, $n, $i){
if($i == $n-1){
// Nothing to do since we're looking at the last element. Just return
// the array as-is.
return $a;
}
else{
$sorted = insertion_sort($a, $n, $i+1);
$el = $a[$i];
// All elements to the right of index $i are assumed to be sorted.
// Now we just have to figure out where $el fits in the sorted array
for($j = $i+1; $j<$n; $j++){
if($el > $sorted[$j]){
// $el is bigger, swap so $el moves to the right in the array.
$sorted[$j-1] = $sorted[$j];
$sorted[$j] = $el;
}
}
return $sorted;
}
}
$arr = array(2,8,9,0,0,2,3);
$sorted_arr = insertion_sort($arr, count($arr), 0);
echo '<pre>';
print_r($sorted_arr);
echo '</pre>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment