请生成javascript版的快速排序
以下是Javascript版的快速排序实现:
function quickSort(arr) {
if (arr.length < 2) {
return arr;
}
const pivot = arr[0]; // 选择第一个元素作为基准值
const left = [];
const right = [];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]); // 小于基准值的放在左边
} else {
right.push(arr[i]); // 大于等于基准值的放在右边
}
}
return quickSort(left).concat(pivot, quickSort(right)); // 递归排序左右两个数组并合并
}
使用方法:
const arr = [5, 3, 7, 2, 8, 4, 9, 1, 6];
const sortedArr = quickSort(arr);
console.log(sortedArr); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
原文地址: https://www.cveoy.top/t/topic/Ss 著作权归作者所有。请勿转载和采集!