lshgdut / essay

随笔记录
0 stars 0 forks source link

chrome下的sort函数的bug #1

Open lshgdut opened 8 years ago

lshgdut commented 8 years ago
[1,3,2,4,6,5,7,9,8,11,10].sort(()=>0); 
// [5, 1, 2, 4, 6, 3, 7, 9, 8, 11, 10]

查阅V8源码发现,排序用了两套算法,数组长度9个是个临界值

https://github.com/v8/v8/blob/master/src/js/array.js#L764

 var QuickSort = function QuickSort(a, from, to) {
    var third_index = 0;
    while (true) {
      // Insertion sort is faster for short arrays.
      if (to - from <= 10) {
        InsertionSort(a, from, to);
        return;
      }
      if (to - from > 1000) {
        third_index = GetThirdIndex(a, from, to);
      } else {
        third_index = from + ((to - from) >> 1);
      }
      ……
}

(待续)

lshgdut commented 5 years ago

链接失效,更新为 https://github.com/v8/v8/blob/master/src/js/array.js#L293