I want quicksort some objects in php.
I am sorting an array of OBJECTS
$object->x;
$object->y;
$object->z;
I want to sort by x first, then y, then z.
This is my quicksort function. Where it takes an array of tasks and sorts by a specific window sortkey (x, y or z) The function returns a sorted array of objects that were sorted by sort type.
private function quicksort($objects, $sortKey) {
if(count($objects) < 2) return $objects;
$left = $right = array();
reset($objects);
$pivot_key = key($objects);
$pivot = array_shift($objects);
foreach($objects as $k => $v) {
if($v->$sortKey < $pivot->$sortKey)
$left[$k] = $v;
else
$right[$k] = $v;
}
return array_merge($this->quicksort($left,$sortKey), array($pivot_key => $pivot), $this->quicksort($right,$sortKey));
}
I can easily sort any column quickly using the recursive quicksort algorithm, but grouping them together and then sorting these subgroups for the nth time really messes with my head.
Is there an algorithm I could look at?
source
share