Created
October 12, 2012 20:12
-
-
Save simensen/3881253 to your computer and use it in GitHub Desktop.
Spiral 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 spiral_sort($input) | |
{ | |
// hack to ensure $output has proper indexes. otherwise | |
// resulting array has proper idx => value but may | |
// actually be accessed incorrectly. | |
$output = $input; | |
$fromFront = 0; | |
$fromBack = count($input) - 1; | |
for ($i = 0; $i < count($input); $i++) { | |
if (0 == $i % 2) { | |
$output[$fromFront++] = $input[$i]; | |
} else { | |
$output[$fromBack--] = $input[$i]; | |
} | |
} | |
return $output; | |
} | |
$input = array(1, 2, 3, 4, 5); | |
print_r($input); | |
print_r(spiral_sort($input)); | |
/* | |
Array | |
( | |
[0] => 1 | |
[1] => 2 | |
[2] => 3 | |
[3] => 4 | |
[4] => 5 | |
) | |
Array | |
( | |
[0] => 1 | |
[1] => 3 | |
[2] => 5 | |
[3] => 4 | |
[4] => 2 | |
) | |
Results without hack: | |
Array | |
( | |
[0] => 1 | |
[4] => 2 | |
[1] => 3 | |
[3] => 4 | |
[2] => 5 | |
) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment