Skip to content

Instantly share code, notes, and snippets.

@assertchris
Created June 15, 2015 03:20
Show Gist options
  • Save assertchris/d34e68b08192c93d9c60 to your computer and use it in GitHub Desktop.
Save assertchris/d34e68b08192c93d9c60 to your computer and use it in GitHub Desktop.
<?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