归并排序
function merge(arr, tempArr, left, mid, right) {
let l_pos = left;
let r_pos = mid + 1;
let pos = left;
while (l_pos <= mid && r_pos <= right) {
if (arr[l_pos] <= arr[r_pos]) {
tempArr[pos++] = arr[l_pos++];
} else {
tempArr[pos++] = arr[r_pos++];
}
}
while (l_pos <= mid) {
tempArr[pos++] = arr[l_pos++];
}
while (r_pos <= right) {
tempArr[pos++] = arr[r_pos++];
}
while (left <= right) {
arr[left] = tempArr[left]
left++;
}
}
function msort(arr, tempArr, left, right) {
if (left < right) {
let mid = (left + right) >> 1;
msort(arr, tempArr, left, mid);
msort(arr, tempArr, mid + 1, right);
merge(arr, tempArr, left, mid, right)
}
}
function merge_sort(arr) {
let n = arr.length;
let tempArr = [];
msort(arr, tempArr, 0, n - 1);
tempArr.length = 0;
}
let arr = [9, 5, 2, 7, 12, 4, 3, 1, 11];
merge_sort(arr);
console.log(arr);