Home > Article > Backend Development > PHP array stable sorting: maintaining the order of equal elements
Stable sorting of PHP arrays can be achieved by: creating a custom comparator that considers the original index when comparing; using the uasort() function to sort the values according to the key and setting the value to the element containing the original index; These methods ensure that equal elements are sorted in the same order as their original order.
PHP array stable sorting: maintaining the order of equal elements
Introduction
Stable sorting ensures that the sorted order of equal elements is the same as the original order. For stable sorting, the following comparisons are valid:
a == b => sort(a) <= sort(b)
The PHP array native sort()
and rsort()
functions are unstable. This article will explore methods for stable sorting.
Method
1. Custom comparator
Use a custom comparator to compare elements when they are equal Original index:
function cmp($a, $b) { if ($a == $b) { return 0; } return $a < $b ? -1 : 1; }
Then use it in the usort()
or uksort()
function:
usort($arr, 'cmp');
2. Use uasort()
uasort()
Sorts values based on keys, ksort()
sorts keys. So you can set the value in the array to an element containing the original index and then sort the keys: The scores are sorted while maintaining the original order of students with the same score:
$indices = array_keys($arr); uasort($arr, function($a, $b) use ($indices) { if ($a == $b) { return 0; } return $indices[array_search($a, $arr)] < $indices[array_search($b, $arr)] ? -1 : 1; });
Output: $scores = [
'John' => 90,
'Mary' => 85,
'Bob' => 85,
'Alice' => 95
];
uasort($scores, function($a, $b) {
if ($a == $b) {
return 0;
}
return $a < $b ? -1 : 1;
});
print_r($scores);
The methods listed above can be implemented in PHP Stable ordering of arrays so that the order of equal elements is maintained.
The above is the detailed content of PHP array stable sorting: maintaining the order of equal elements. For more information, please follow other related articles on the PHP Chinese website!