快速排序模板,方便刷题时使用,需要背诵并熟练使用,目前仅写了java和JavaScript的版本,支持do while结构的语言都可以方便的写出,没有支持do while的语言的模板不太优雅,没有列出。
java版本 升序
void qsort(int[] nums, int l, int r) {
if (l >= r) return;
int x = nums[l], i = l - 1, j = r + 1;
while (i < j) {
do i++; while (nums[i] < x);
do j--; while (nums[j] > x);
if (i < j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
qsort(nums, l, j);
qsort(nums, j + 1, r);
}
javascript版本 升序
function qsort(nums, l, r) {
if (l >= r) return;
if (l >= r) return;
let x = nums[l], i = l - 1, j = r + 1;
while (i < j) {
do i++; while (nums[i] < x);
do j--; while (nums[j] > x);
if (i < j) {
let t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
qsort(nums, l, j);
qsort(nums, j + 1, r);
}