在对 Array.sort()
进行深入研究时
发现sort()
方法在运行时的插入排序算法(长度<=22时使用这个算法)有差异。
先来看V8源码的运行
V8源码第710行:
var InsertionSort = function InsertionSort(a, from, to) {
for (var i = from + 1; i < to; i++) {
var element = a[i];
for (var j = i - 1; j >= from; j--) {
var tmp = a[j];
var order = comparefn(tmp, element);
if (order > 0) {
a[j + 1] = tmp;
} else {
break;
}
}
a[j + 1] = element;
}
};
于是我写了测试代码来检测
测试代码:
var a = [77,33,44,55,66]
var InsertionSort = function InsertionSort(a, from, to) {
for (var i = from + 1; i < to; i++) {
var element = a[i];
for (var j = i - 1; j >= from; j--) {
var tmp = a[j];
var order = comparefn(tmp, element);
if (order > 0) {
a[j + 1] = tmp;
} else {
break;
}
}
a[j + 1] = element;
}
};
function comparefn(a,b){
if(a<b)return -1;
if (a>b)return 1;
return 0;
}
InsertionSort(a,0,5)
console.log(a)
测试中compartfn
它的比较顺序为
次数 | a | b | 备注 |
---|
1 | 77 | 33 | [33,77,44,55,66] |
2 | 77 | 44 | [33,77,44,55,66] |
3 | 33 | 44 | [33,44,77,55,66] |
4 | 77 | 55 | [33,44,77,55,66] |
5 | 44 | 55 | [33,44,55,77,66] |
6 | 77 | 66 | [33,44,55,77,66] |
7 | 55 | 66 | [33,44,55,66,77] |
而在实际使用Array.sort()
中却不是这上顺序
Array.sort()
代码检测:
let c = [77,33,44,66,55]
c.sort((a,b)=>{
if (a<b){ console.log(c); return -1;}
if (a>b){ console.log(c); return 1;}
return 0;
})
比较顺序为
次数 | a | b | 备注 |
---|
1 | 33 | 77 |
2 | 44 | 33 |
3 | 44 | 77 |
4 | 44 | 33 |
5 | 66 | 44 |
6 | 66 | 77 |
7 | 55 | 66 |
8 | 55 | 44 |
这个是实现上有差异吗?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…