Created
October 12, 2015 07:56
-
-
Save joequery/2433098abe3b6e141492 to your computer and use it in GitHub Desktop.
Recursive PHP Insertion Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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