We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Array.prototype.sort深挖的内容比较多。
var array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // [1, 100000, 21, 30, 4]
compareFn
["你", 'Z'].sort(); // ["你", "Z"] ["你", 'Z'].sort((a, b) => a.codePointAt(0) - b.codePointAt(0)) // ["Z", "你"]
这导致各个浏览器实现不一致,甚至不同版本的浏览器也不一样。
// In-place QuickSort algorithm. // For short (length <= 22) arrays, insertion sort is used for efficiency.
// In-place QuickSort algorithm. // For short (length <= 10) arrays, insertion sort is used for efficiency.
V8 v7.0 / Chrome 70
TimSort
describes our journey to move V8 to a stable algorithm and make performance more predictable.
sort
各浏览器也都基本采用了稳定排序算法:
IE6+: 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 long arrays (>512 elements)
The text was updated successfully, but these errors were encountered:
排序算法处理考虑时间复杂度,空间复杂度还需要考虑稳定性。
排序算法稳定性的简单形式化定义为:如果Ai = Aj,排序前Ai在Aj之前,排序后Ai还在Aj之前,则称这种排序算法是稳定的。 通俗地讲就是保证排序前后两个相等的数的相对顺序不变。
排序算法如果是稳定的,那么从一个键上排序,然后再从另一个键上排序,前一个键排序的结果可以为后一个键排序所用。基数排序就是这样,先按低位排序,逐次按高位排序,低位排序后元素的顺序在高位也相同时是不会改变的。
逐步统一:
摘自Is there an ideal comparison sort?
Sorry, something went wrong.
No branches or pull requests
Array.prototype.sort深挖的内容比较多。
一、语法
compareFn
实参。二、采用什么算法?
2.1 现状
这导致各个浏览器实现不一致,甚至不同版本的浏览器也不一样。
Chrome比较折腾
V8 v7.0 / Chrome 70
采用TimSort
。为啥这么折腾呢?
2.2 未来
sort
方法必须采用稳定的排序算法。让排序结果可预期。
目前还没万能的方式,看各位取舍了。
各浏览器也都基本采用了稳定排序算法:
参考
The text was updated successfully, but these errors were encountered: