How to quickly sort by multiple columns

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?

+3
source share
3 answers

, . , , , (.. x , y ..).

, ​​ . , / .

, , :

    if($v->$sortKey < $pivot->$sortKey)

$v β†’ $sortKey < $pivot β†’ $sortKey, , .

    if (smaller($v, $pivot))

smaller() .

private function smaller($obj1, $obj2) {
    if ($obj1->x < $obj2->x)
        return true;
    if ($obj1->x > $obj2->x)
        return false;
    if ($obj1->y < $obj2->y)
        return true;
    if ($obj1->y > $obj2->y)
        return false;
}

... . , x, , x ( , ), y.

+7

? http://us3.php.net/usort?

usort() , , .

+2

Sorting algorithms do not depend on the mechanics of comparison, but only on the fact that it returns a sequential order. You need a sorting procedure that allows you to specify your own comparison function.

Php provides three: usort (), uasort (), and uksort ().

+1
source

Source: https://habr.com/ru/post/1769005/


All Articles