What is the stability of Array.sort() across different browsers?
The stability of the Array.sort() method, which determines whether the order of equal elements is preserved after sorting, varies among different browsers:
As of ES2019, the sort method is required to be stable:
This means that equal elements in the array will maintain their relative order after sorting.
Before ES2019, the stability was browser-dependent:
Note that some versions of Chrome switched between stable and unstable sorts based on array size:
Prior to Chrome 70, the engine used a stable sort for small arrays and an unstable one for larger arrays. This can be verified using the following test case:
<code class="js">function Pair(_x, _y) { this.x = _x; this.y = _y; } function pairSort(a, b) { return a.x - b.x; } // Create an array with enough entries to trigger the "more efficient" sort method var y = 0; var check = []; while (check.length < 100) { check.push(new Pair(Math.floor(Math.random() * 3) + 1, ++y)); } check.sort(pairSort); // Check for instability by comparing the order of equal elements var min = {}; var issues = 0; for (var i = 0; i < check.length; ++i) { var entry = check[i]; var found = min[entry.x]; if (found) { if (found.y > entry.y) { console.log("Unstable at " + found.i + ": " + found.y + " > " + entry.y); ++issues; } } else { min[entry.x] = {x: entry.x, y: entry.y, i: i}; } } // Log stability status if (!issues) { console.log("Sort appears to be stable"); }</code>
This test will demonstrate instability in previous versions of Chrome and other browsers that implemented unstable sorts.
The above is the detailed content of Is Array.sort() stable across different browsers?. For more information, please follow other related articles on the PHP Chinese website!