function mergeSort(target) {
if (target.length < 2) {
return target;
}
const midIndex = Math.floor(target.length / 2);
return merge(
mergeSort(target.slice(0, midIndex)),
mergeSort(target.slice(midIndex))
)
}
function merge(left, right) {
let temp = []
while (left.length && right.length) {
if (left[0] <= right[0]) {
temp.push(left.shift());
} else {
temp.push(right.shift());
}
}
return temp.concat(left).concat(right)
}
const arr = [1, 3, 7, 2, 5]
console.log(mergeSort(arr)) //[ 1, 2, 3, 5, 7 ]
javascript-实现归并排序算法
于 2024-06-22 16:39:19 首次发布