Home > Web Front-end > JS Tutorial > Is Array.sort() stable across different browsers?

Is Array.sort() stable across different browsers?

Linda Hamilton
Release: 2024-11-02 13:38:30
Original
296 people have browsed it

Is Array.sort() stable across different browsers?

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:

  • IE 6 : Stable
  • Firefox < 3: Unstable
  • Firefox >= 3: Stable
  • Chrome < 70: Unstable
  • Chrome >= 70: Stable
  • Opera < 10: Unstable
  • Opera >= 10: Stable
  • Safari 4: Stable
  • Edge: Unstable for arrays with more than 512 elements

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template