简介:简要介绍快速排序的实现
快速排序和寻找数组中第 K 大/小的元素,核心内容都是进行分支操作,将数据分割成比 pivot
元素小和比 pivot
元素大的两部分。
下面是升序排列的分治函数,这段代码里依次做了以下的事情:
pivot
pivot
的元素pivot
的元素pivot
const partition = (nums: number[], left: number, right: number) => {
const pivot = nums[left];
while (left < right) {
while (left < right && pivot <= nums[right]) {
right--;
}
nums[left] = nums[right];
while (left < right && pivot >= nums[left]) {
left++;
}
nums[right] = nums[left];
}
nums[left] = pivot;
return left;
}
如果是需要降序排列的结果,只需反转 pivot
与 nums[left|right]
的比较符号即可。
递归分治即可:
const quickSort = (nums: number[]) => {
const recurse = (left, right) => {
if (left >= right) {
return;
}
const pivotIndex = partition(left, right);
recurse(left, pivotIndex - 1);
recurse(pivotIndex + 1, right);
}
recurse(0, nums.length - 1);
return nums;
}