Home >Web Front-end >JS Tutorial >Is Array.sort() Method Stable Across Different Browsers?
The Array.sort() method is a powerful tool for sorting arrays in ascending or descending order. However, the stability of this method, which ensures that elements with equal values retain their original relative order, is not guaranteed by the ECMAScript specification.
Firefox has consistently used a stable sort algorithm, ensuring that elements with the same value maintain their relative ordering after sorting.
Internet Explorer has also implemented a stable sort algorithm, preserving the original order of elements with equal values.
Chrome's sort algorithm has evolved over time. Prior to version 70, Chrome used an unstable sort for larger arrays, which could lead to elements with the same value being reordered. However, in Chrome versions 70 and later, the sort algorithm has been changed to be stable for both large and small arrays.
Safari has implemented a stable sort algorithm, ensuring that elements with equal values remain in their original order.
As of ECMAScript 2019, the sort method is required to be stable. However, in earlier versions of ECMAScript (ES2018 and earlier), the stability of the sort method was not explicitly specified, allowing individual browsers to choose their own implementation.
The stability of the Array.sort() method varies across different browsers. Firefox, IE 6/7/8, Chrome versions 70 and later, and Safari all provide stable sorting behavior. However, Chrome versions prior to 70 used an unstable sort algorithm for large arrays. It's important to be aware of these browser-specific differences when using the Array.sort() method.
The above is the detailed content of Is Array.sort() Method Stable Across Different Browsers?. For more information, please follow other related articles on the PHP Chinese website!