仅仅提供代码实现,原理请问度娘。
1、 数据和工具类
module.exports.list = [9, 3, 4, 32, 42, 3, 45, 33, 2, 76, 89, 34];
module.exports.swap = function (list, i, j) {
let temp = list[i];
list[i] = list[j];
list[j] = temp;
};
module.exports.display = function (list) {
let str = "";
for (let i = 0; i < list.length; i++) {
str += list[i] + ", ";
}
console.log(str.replace(/, $/, ""));
};
2、归并实现
/**
* 归并排序
*/
const { list, swap, display } = require("./utils/common");
function mergeSort(list) {
if (!list || list.length == 1) {
return list || [];
}
//开始对半切分数组
let mid = Math.trunc(list.length / 2);
let leftList = mergeSort(list.slice(0, mid));
let rightList = mergeSort(list.slice(mid, list.length));
return merge(leftList, rightList);
}
/**
* 两个子数组进行合并排序。其中 leftList, lastList 分别有序。
*/
function merge(leftList, rightList) {
//进行合并并且排序
let newList = [];
let minLength = Math.min(leftList.length, rightList.length);
//两个有序数组的合并。
let i = 0,
j = 0;
while (true) {
if (leftList[i] < rightList[j]) {
newList.push(leftList[i]);
i++;
} else {
newList.push(rightList[j]);
j++;
}
if (i >= leftList.length || j >= rightList.length) {
break;
}
}
newList.push(...leftList.slice(i, leftList.length));
newList.push(...rightList.slice(j, rightList.length));
// console.log("newList: ",newList);
return newList;
}
let newList = mergeSort(list);
display(newList);