Home  >  Article  >  Web Front-end  >  Is `Array.sort()` Stable Across Different Browsers?

Is `Array.sort()` Stable Across Different Browsers?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 11:42:02304browse

Is `Array.sort()` Stable Across Different Browsers?

The Stability of the Array.sort() Method in Different Browsers

The ECMA Script specification leaves the choice of sorting algorithm and stability to the browser's implementation. As such, the stability of Array.sort() varies across different browsers.

Browser Stability Evaluation:

IE6 : Stable

Firefox:

  • < 3: Unstable
  • >= 3: Stable

Chrome:

  • < 70: Unstable
  • >= 70: Stable

Opera:

  • < 10: Unstable
  • >= 10: Stable

Safari:

  • 4: Stable

Edge:

  • Stable for arrays with less than 512 elements
  • Unstable for longer arrays

Stable vs. Unstable Sorting:

A stable sorting algorithm maintains the relative order of equal elements. In an unstable sort, equal elements can have their order reversed after sorting.

Implications of Stability:

The instability of Array.sort() in certain browser versions can affect the reliability of sorting code. For example, when sorting by multiple criteria, instability can lead to unpredictable results.

Additional Resources:

  • [Fast Stable Sorting Algorithm Implementation in JavaScript](https://www.rosettacode.org/wiki/Sorting_algorithms/Counting_sort#JavaScript)
  • [Test Case for Identifying V8's Sorting Algorithm Behavior](https://gist.github.com/cowboy/1672257)

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!

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