NodeJS 14.4.0对Array使用什么排序算法?对包含四个元素的数组进行排序



我不相信这是重复的Javascript's sort()是如何工作的?

let arr = [3, 4, 2, 1];
arr.sort((second,first) => {
console.log([first, second]);
if (first>second) {
return -1; // switch them
}
return 0; // don't switch them
});
console.log(arr);

这返回

[ 3, 4 ]
[ 4, 2 ]
[ 4, 2 ] <---- Why is this output twice?
[ 3, 2 ]
[ 3, 1 ]
[ 2, 1 ]
[ 1, 2, 3, 4 ]

我试图找出什么算法NodeJS(14.4.0)是使用数组。用我的输入排序?

在这篇文章中,v8引擎显然使用Timsort进行排序:

https://v8.dev/blog/array-sort timsort

最新更新