Quoted from here:
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
In my opinion, cmp_function
needs only to return 1
if the first is greater than the second.
Why does it need all 3
cases ?
UPDATE
function bubble($list)
{
$length = count($list) - 2;
$sorted = false;
while(!$sorted)
{
$sorted = true;
foreach(range(0,$length) as $i)
{
if($list[$i] > $list[$i + 1])
{
开发者_开发百科 $sorted = false;
list($list[$i],$list[$i + 1]) = array($list[$i + 1],$list[$i]);
}
}
}
return $list;
}
So that it can distinguish between <
, ==
and >
.
This is similar to the requirements on the callback for e.g. C's qsort
(for all I know, usort
may be implemented using qsort
internally).
It is possible to write a search routine that only needs a two-valued predicate, but usort
happens not to be one of them.
In fact you're almost right, you don't need 3 differents values.
But, 1 single value isn't sufficient, you need 2 values:
- 1(true) <=> first > second
- 0(false) <=> first <= second
精彩评论