Skip to content

Instantly share code, notes, and snippets.

@olvlvl
Created January 7, 2012 14:23
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 olvlvl/1574867 to your computer and use it in GitHub Desktop.
Save olvlvl/1574867 to your computer and use it in GitHub Desktop.
Stable sort function
/*
* 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);
}
@MrStonedOne
Copy link

No documentation on the args for the callable.

3/10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment