【问题标题】:What sort algorithm is NodeJS 14.4.0 using for Array.sort on array of four elementsNodeJS 14.4.0 使用什么排序算法对四个元素的数组进行 Array.sort
【发布时间】:2021-05-21 11:52:00
【问题描述】:

我不相信这是复制品 How does Javascript's sort() work?

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 使用什么算法?

【问题讨论】:

标签: javascript node.js sorting


【解决方案1】:

作为post 中的注释,v8 引擎显然使用 Timsort 进行排序:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 2018-08-26
    • 2010-10-22
    相关资源
    最近更新 更多