目录
一、思想
将数列分成两半,假设每一个子序列都是按顺序排列的,那么我们可以从两个序列的第一个元素开始进行比较,将较大(或较小)的数放入合并后的数组,直到两个数组都遍历完,由于两个子序列是有序的,得到的合并后的数列也是有序的。然后我们回到假设,实际上分成两个子序列不一定是有序的,我们可以将其作为一个新的序列,进行内部分割及排序,类推直到子序列只有一个或零个元素。
二、实现
js
/**
* 对数列list进行分割
*/
let mergeSort = (list) => {
let l = list.length;
if (l <= 1) return list;
let substrIdx = Math.floor(l / 2);
let subList1 = list.slice(0, substrIdx);
let subList2 = list.slice(substrIdx, l);
return merge(mergeSort(subList1), mergeSort(subList2)); //将子序列分别"合并排序"后进行合并
}
/**
* 两个有序数列的合并
*/
let merge = (list1, list2) => {
let l1 = list1.length;
let l2 = list2.length;
let idx1 = 0;
let idx2 = 0;
let ret = [];
do {
if (list1[idx1] !== undefined && (list2[idx2] === undefined || list1[idx1] >= list2[idx2])) {
ret.push(list1[idx1]);
idx1++;
} else if (list2[idx2] !== undefined) {
ret.push(list2[idx2]);
idx2++;
}
} while (idx1 < l1 || idx2 < l2);
return ret;
}
//模拟输入
let input = [1, 2, 4, 89, 3, 42, 4, 74, 5, 20, 6, 8, 7];
console.log('Input: ', input);
let result = mergeSort(input);
console.log('Output:', result);