<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="author" content="杨欣">
<title></title>
</head>
<body>
<script>
// 递归分组
function mergeSort(arr) {
if (arr.length <= 1) {
return arr
}
let midIndex = arr.length / 2 | 0;
let leftArr = arr.slice(0, midIndex);
let rightArr = arr.slice(midIndex, arr.length);
return merge(mergeSort(leftArr), mergeSort(rightArr))
}
// 合并
function merge(leftArr, rightArr) {
let res = [];
while (leftArr.length && rightArr.length) {
leftArr[0] >= rightArr[0] ? res.push(rightArr.shift()) : res.push(leftArr.shift())
}
while (leftArr.length) {
res.push(leftArr.shift())
}
while (rightArr.length) {
res.push(rightArr.shift())
}
return res
}
console.log(mergeSort([1, 9, 7, 3, 4, 5, 8, 6]));
</script>
</body>
</html>