首页 > 解决方案 > NodeJS 14.4.0 使用什么排序算法对四个元素的数组进行 Array.sort

问题描述

我不相信这是这个的副本 Javascript 的 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) 使用我的输入对 Array.sort 使用什么算法?

标签: javascriptnode.jssorting

解决方案


正如这篇文章中的注释,v8 引擎显然使用 Timsort 进行排序:

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


推荐阅读