用js 写一个快速排序
时间: 2023-05-24 22:02:10 浏览: 45
Sure, here's an implementation of quicksort in JavaScript:
function quicksort(arr) {
if (arr.length <= 1) return arr;
const pivot = arr[Math.floor(Math.random() * arr.length)];
const less = [];
const more = [];
const equal = [];
for (let num of arr) {
if (num < pivot) less.push(num);
else if (num > pivot) more.push(num);
else equal.push(num);
}
return quicksort(less).concat(equal, quicksort(more));
}
const unsortedArr = [5, 3, 8, 1, 9, 2];
const sortedArr = quicksort(unsortedArr);
console.log(sortedArr);
This implementation uses the random selection of a pivot to sort the elements of the array into three sub-arrays: elements less than the pivot, elements equal to the pivot, and elements greater than the pivot. These sub-arrays are then concatenated after they have been sorted recursively using the same quicksort function.