AcWing 787. 归并排序
原题链接
简单
作者:
一个不正经的程序员
,
2024-11-18 23:02:24
,
所有人可见
,
阅读 1
// 归并排序模板
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
function mergeSort(arr, start = 0, end = arr.length) {
if (end - start <= 1) return arr.slice(start, end);
const mid = Math.floor((start + end) / 2);
const left = mergeSort(arr, start, mid);
const right = mergeSort(arr, mid, end);
return sort(left, right);
}
function sort(left, right) {
const tem = [];
let l = 0, r = 0;
while (l < left.length && r < right.length) {
tem.push(left[l] < right[r] ? left[l++] : right[r++]);
}
tem.push(...left.slice(l), ...right.slice(r));
return tem;
}
let arr = []
readline.on('line', (line) => {
arr.push(line.trim());
if(arr.length === 2){
let tem = arr[1].split(' ').map(v=> Number(v));
console.log(mergeSort(tem,0,tem.length).join(' '));
readline.close()
}
})