var arr = [ 0, 0, 1, 2, 3, 4, 5, 6, 12, 22, 123, 333, 333, 444, 555, 666, 777, 888, 999];
function shellSort(arr) {
var arrLenght = arr.length;
var splitNum = Math.floor(arrLenght / 2);
var countAll = 0;
var swapAll = 0;
function swap(arr, n1, n2) {
if(arr[n1] > arr[n2]){
[arr[n1], arr[n2]] = [arr[n2], arr[n1]];
swapAll += 1;
return true;
}
return false;
}
function one() {
// +6 步进比较的模式 上下
//0 1 2 3 4 5
//6 7 8 9 10 11
for(let i = 0; i < arrLenght; i++){
swap(arr, i, i+splitNum);
countAll += 1;
}
}
one();
function two() {
// +2 步进比较的模式 线性
// 0 2, 4 6, 8 10, 1 3, 5 7, 9 11
for(let i=0; i<1; i++){
for(let n = i; n < arrLenght; n += 2){
swap(arr, n, n+2);
countAll += 1;
}
}
}
two();
function three() {
// 插入排序
for(let i = 0; i < arrLenght; i++){
var index = i;
while(swap(arr, index, index-1)){
index--;
countAll += 1;
}
}
}
three();
console.log('swapAll: ' + swapAll);
console.log('forLoop: ' + countAll);
return arr;
}
console.log(shellSort(arr));
swapAll: 169
forLoop: 198
[ 999, 888, 777, 666, 555, 444, 333, 333, 123, 22, 12, 6, 5, 4, 3, 2, 1, 0, 0 ]