Created
June 15, 2015 03:20
-
-
Save assertchris/d34e68b08192c93d9c60 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 bubble_recursive(array $items, $iterations = null) { | |
if ($iterations === null) { | |
$iterations = count($items); | |
} | |
$items = bubble_recursive_inner($items, $iterations); | |
if ($iterations > 1) { | |
return bubble_recursive($items, $iterations - 1); | |
} | |
return $items; | |
} | |
function bubble_recursive_inner(array $items, $iterations, $i = 1) { | |
if ($i < $iterations) { | |
$prev = $items[$i - 1]; | |
$next = $items[$i]; | |
if ($prev > $next) { | |
$items[$i] = $prev; | |
$items[$i - 1] = $next; | |
} | |
return bubble_recursive_inner($items, $iterations, $i + 1); | |
} | |
return $items; | |
} | |
$items = [1, 6, 2, 5, 3, 4]; | |
bubble_recursive($items); // [1, 2, 3, 4, 5, 6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment