Home  >  Article  >  Web Front-end  >  Is JavaScript\'s Array.sort() Method Stable Across All Browsers?

Is JavaScript\'s Array.sort() Method Stable Across All Browsers?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 01:42:30180browse

Is JavaScript's Array.sort() Method Stable Across All Browsers?

Stability of Array.sort() Method Across Browsers

Introduction

Array sorting is a fundamental operation in JavaScript. However, the stability of the Array.sort() method varies across different browsers.

ECMA Script and Stability

The ECMA Script specification does not define a specific sorting algorithm or specify whether the sort should be stable. This means different browsers may implement different approaches, resulting in varying stability characteristics.

Stability Across Specific Browsers

  • IE 6-8: Stable
  • Firefox < 3: Unstable
  • Firefox >= 3: Stable
  • Chrome < 70: Unstable
  • Chrome >= 70: Stable
  • Opera < 10: Unstable
  • Opera >= 10: Stable
  • Safari 4: Stable
  • Edge (large arrays): Unstable

Example Test Case

To demonstrate the stability of the sort method, a test case involving pairs of values can be created:

<code class="javascript">function Pair(_x, _y) {
    this.x = _x;
    this.y = _y;
}
function pairSort(a, b) {
    return a.x - b.x;
}
var check = [];
for (var i = 0; i < 100; ++i) {
    check.push(new Pair(Math.random() * 3 + 1, ++y));
}
check.sort(pairSort);</code>

If the sort is stable, the values will be sorted based on their x values first, and then by their y values, such that the original order of values with the same x value is preserved. Conversely, an unstable sort may result in different orders for values with the same x value.

The above is the detailed content of Is JavaScript\'s Array.sort() Method Stable Across All Browsers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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