Skip to content

Instantly share code, notes, and snippets.

@simensen
Created October 12, 2012 20:12
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 simensen/3881253 to your computer and use it in GitHub Desktop.
Save simensen/3881253 to your computer and use it in GitHub Desktop.
Spiral Sort
<?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