Created
January 7, 2012 14:23
-
-
Save olvlvl/1574867 to your computer and use it in GitHub Desktop.
Stable sort function
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
/* | |
* This file is part of the ICanBoogie package. | |
* | |
* (c) Olivier Laviale <olivier.laviale@gmail.com> | |
* | |
* For the full copyright and license information, please view the LICENSE | |
* file that was distributed with this source code. | |
*/ | |
namespace ICanBoogie; | |
/** | |
* Sorts an array using a stable sorting algorithm while preserving its keys. | |
* | |
* A stable sorting algorithm maintains the relative order of values with equal keys. | |
* | |
* The array is always sorted in ascending order but one can use the array_reverse() function to | |
* reverse the array. Also keys are preserved, even numeric ones, use the array_values() function | |
* to create an array with an ascending index. | |
* | |
* @param array &$array | |
* @param callable $picker | |
*/ | |
function stable_sort(&$array, $picker=null) | |
{ | |
static $transform, $restore; | |
if (!$transform) | |
{ | |
$transform = function(&$v, $k) | |
{ | |
$v = array($v, $k, $v); | |
}; | |
$restore = function(&$v, $k) | |
{ | |
$v = $v[2]; | |
}; | |
} | |
if ($picker) | |
{ | |
array_walk | |
( | |
$array, function(&$v, $k) use ($picker) | |
{ | |
$v = array($picker($v), $k, $v); | |
} | |
); | |
} | |
else | |
{ | |
array_walk($array, $transform); | |
} | |
asort($array); | |
array_walk($array, $restore); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No documentation on the args for the callable.
3/10