javascript
归并操作,也叫归并算法,指的是将两个顺序序列合并成一个顺序序列的方法。
如 设有数列{6,202,100,301,38,8,1}
初始状态:6,202,100,301,38,8,1
第一次归并后:{6,202},{100,301},{8,38},{1},比较次数:3;
第二次归并后:{6,100,202,301},{1,8,38},比较次数:4;
第三次归并后:{1,6,8,38,100,202,301},比较次数:4;
总的比较次数为:3+4+4=11;
逆序数为14;
javascript
//一一比较 两两比较 四四比较
function mergeSort(arr) {
if (arr.length < 2) {
return;
}
var step = 1;//滑块
var left, right;
while (step < arr.length) {
left = 0;
right = 0+step;
while (right + step <= arr.length) {
//mergeArrays(arr,startLeft, stopLeft, startRight, stopRight)
mergeArrays(arr, left, left+step, right, right+step);
left = right + step;
right = left + step;
}
//右边不一定到尾了,没有到尾继续合并
if (right < arr.length) {
//mergeArrays(arr,startLeft, stopLeft, startRight, stopRight)
mergeArrays(arr, left, left+step, right, arr.length);
}
//滑块变大
step *= 2;
}
return arr;
}
function mergeArrays(arr,startLeft, stopLeft, startRight, stopRight) {
var rightArr = new Array(stopRight - startRight + 1);
var leftArr = new Array(stopLeft - startLeft + 1);
//填充左数组
k = startRight;
for (var i = 0; i < (rightArr.length-1); ++i) {
rightArr[i] = arr[k];
++k;
}
//填充有数组
k = startLeft;
for (var i = 0; i < (leftArr.length-1); ++i) {
leftArr[i] = arr[k];
++k;
}
rightArr[rightArr.length-1] = Infinity; // 哨兵值
leftArr[leftArr.length-1] = Infinity; // 哨兵值
//左右数组起始位置
var m = 0;
var n = 0;
for (var k = startLeft; k < stopRight; ++k) {//左右数组两两比较
if (leftArr[m] <= rightArr[n]) {
arr[k] = leftArr[m];
m++;
} else {
arr[k] = rightArr[n];
n++;
}
}
}
mergeSort([4, 7, 6, 5, 3, 2, 8, 1]);