跳到主要内容

常见的排序算法

归并排序

var sortArray = function (nums) {
return mergesort(nums, 0, nums.length - 1);
};
function mergesort(nums, left, right) {
if (left >= right) return nums;
let mid = (left + right) >> 1;
mergesort(nums, left, mid);
mergesort(nums, mid + 1, right);
return merge(nums, left, mid, right);
}
function merge(nums, left, mid, right) {
let ans = [];
let cur = 0,
i = left,
j = mid + 1;
while (i <= mid && j <= right) {
if (nums[i] < nums[j]) {
ans[cur++] = nums[i++];
} else {
ans[cur++] = nums[j++];
}
}
while (i <= mid) {
ans[cur++] = nums[i++];
}
while (j <= mid) {
ans[cur++] = nums[j++];
}
for (let i = 0; i < ans.length; i++) {
nums[i + left] = ans[i];
}
return nums;
}