用js写个快排
时间: 2023-09-18 09:09:18 浏览: 31
好的,以下是使用JavaScript实现快速排序的示例代码:
```javascript
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
}
let pivotIndex = Math.floor(arr.length / 2);
let pivot = arr[pivotIndex];
let left = [];
let right = [];
for (let i = 0; i < arr.length; i++) {
if (i === pivotIndex) {
continue;
}
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat(pivot, quickSort(right));
}
// 示例
const unsortedArray = [4, 7, 1, 3, 9, 2, 5, 8, 6];
const sortedArray = quickSort(unsortedArray);
console.log(sortedArray); // 输出 [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
这个示例代码使用了递归的方法实现快速排序,主要思路是选择数组中间的一个元素作为基准点(pivot),然后将数组中小于基准点的元素放入左边数组(left),大于基准点的元素放入右边数组(right),然后递归调用 quickSort 函数对左右数组进行排序。最后,将排好序的左右数组和基准点拼接起来,就得到了最终的排序结果。