-
-
Notifications
You must be signed in to change notification settings - Fork 229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
快速排序 #195
Comments
|
需额外空间,非原地排序/**
* 快速排序
* @param arr 待排序数组
* @returns
*/
const quickSort = function (arr: number[]): number[] {
if (arr.length <= 1) {
return arr;
}
const pivotIndex = Math.floor(arr.length / 2);
// 从数组中取出我们的"基准"元素
const pivot = arr.splice(pivotIndex, 1)[0];
const leftArr: number[] = [];
const rightArr: number[] = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] <= pivot) {
leftArr.push(arr[i]);
} else {
rightArr.push(arr[i]);
}
}
// 至此,我们将数组分成了left和right两个部分,中间的一个元素pivot之前被删了,现在要加回来
return [...quickSort(leftArr), pivot, ...quickSort(rightArr)];
};
// test
const arr = [98, 42, 25, 54, 15, 3, 25, 72, 41, 10, 121];
console.log(quickSort(arr)); |
function quick_sort(q, l, r) {
if (l >= r) return;
let i = l - 1,
j = r + 1,
x = q[(i + j) >> 1];
while (i < j) {
do i++;
while (q[i] < x);
do j--;
while (q[j] > x);
if (i < j) {
[q[i], q[j]] = [q[j], q[i]];
}
}
quick_sort(q, l, j), quick_sort(q, j + 1, r);
}
const num = [3, 4, 2, 1, 6, 7, 4];
quick_sort(num, 0, num.length - 1);
console.log(num); |
function quickSort(arr) {
if (arr.length < 2) return arr;
const left = [],
right = [],
cur = arr.splice(0, 1);
for (let item of arr)
item > cur ? right.push(item) : left.push(item);
return quickSort(left).concat(cur, quickSort(right));
}
const arr = [98, 42, 25, 54, 15, 3, 25, 72, 41, 10, 121];
console.log(quickSort(arr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: