Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For an unstable sort, does it matter how I treat equal items?

Tags:

php

sorting

I'm trying to simplify a contrived callback function in PHP for sorting.

function my_sort($a, $b) {
    if($a == $b) return 0;
    return $a < $b ? 1 : -1;
}

According to the PHP documentation on usort, the order is undefined when you return equal.

Does this mean that I can skip testing for equality altogether?

function my_sort($a, $b) {
    return $a < $b ? 1 : -1;
}
like image 844
Martin Avatar asked Dec 06 '25 02:12

Martin


1 Answers

As @lanzz said, writing sort function that way will make it less efficient. Equal elements will be considered not-equal (= that should be reordered), hence the number of the sorting function's calls will be higher.

For example:

$aops = 0;
$x = array(1, 1, 1, -1, -1, -1, 0, 0, 0);
usort($x, function($a, $b) use (&$aops) { $aops++; return $a < $b ? -1 : 1; });
var_dump($aops); // 34

$bops = 0;
$x = array(1, 1, 1, -1, -1, -1, 0, 0, 0);
usort($x, function($a, $b) use (&$bops) { $bops++; return $a === $b ? 0 : ($a < $b ? -1 : 1); });
var_dump($bops); // 17

It's obviously not a problem, though, if all elements of the sorted array are guaranteed to be unique.

like image 117
raina77ow Avatar answered Dec 08 '25 14:12

raina77ow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!