简体   繁体   English

使用带有比较函数的 Array.prototype.sort() 时的排序算法是什么

[英]What's the sorting algorithm when using Array.prototype.sort() with a compare function

I've known that when using Array.prototype.sort() , different browsers have their own sorting algorithm implementation.我知道在使用Array.prototype.sort() ,不同的浏览器有自己的排序算法实现。 But I'm curious, does using it with a compare function still utilizes the same sorting algorithm as using without the compare function?但我很好奇,将它与比较函数一起使用是否仍然使用与不使用比较函数相同的排序算法? If it does, does the compare function have a performance impact on the algorithm?如果是,比较函数对算法的性能有影响吗? And if it doesn't, what sorting algorithm does it use?如果没有,它使用什么排序算法?

Scenario eg场景例如

const arr = [23, 1, 5, 2, 10, 2]
arr.sort((a, b) => a - b)

Yes, it's the same sort function.是的,它是相同的排序功能。 Technically when not passing a comparison function it is still using a comparison function as a default.从技术上讲,当不传递比较函数时,它仍然使用比较函数作为默认值。 Mozilla has a pretty detailed explanation of the comparison function it uses when none is supplied: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description当没有提供时,Mozilla 对它使用的比较函数有一个非常详细的解释: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM