用 JS 写一个快速排序的代码
时间: 2023-08-31 18:42:04 浏览: 64
### 回答1:
答:var quickSort = function(arr) {
if (arr.length <= 1) {
return arr;
}
var pivotIndex = Math.floor(arr.length / 2);
var pivot = arr.splice(pivotIndex, 1)[0];
var left = [], right = [];
for (var i = 0; i < arr.length; i++){
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat([pivot], quickSort(right));
};
### 回答2:
下面是使用 JavaScript 编写的快速排序算法代码:
```javascript
function quickSort(array) {
if (array.length <= 1) {
return array; // 如果数组只有一个元素或为空,则无需排序
}
const pivotIndex = Math.floor(array.length / 2); // 取数组中间元素为基准值
const pivot = array.splice(pivotIndex, 1)[0]; // 从数组中把基准值移除
const left = []; // 用于存放小于基准值的元素
const right = []; // 用于存放大于基准值的元素
for (let i = 0; i < array.length; i++) {
if (array[i] < pivot) {
left.push(array[i]);
} else {
right.push(array[i]);
}
}
return quickSort(left).concat([pivot], quickSort(right)); // 递归排序左右两部分,并拼接结果
}
// 示例用法
const unsortedArray = [5, 9, 3, 1, 8, 2, 7, 4, 6];
const sortedArray = quickSort(unsortedArray);
console.log(sortedArray); // 输出 [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
以上代码使用了递归的方式实现快速排序算法。具体步骤如下:
1. 如果数组长度小于等于 1,则直接返回数组(无需排序)。
2. 选取数组中间的元素作为基准值,并将其从原数组中移除。
3. 创建两个新数组 `left` 和 `right`,分别用于存放小于基准值和大于基准值的元素。
4. 遍历原数组中剩余的元素,将小于基准值的元素放入 `left` 数组,将大于基准值的元素放入 `right` 数组。
5. 递归调用 `quickSort` 函数对 `left` 和 `right` 数组进行排序。
6. 将排序后的 `left` 数组、基准值和排序后的 `right` 数组按顺序拼接起来,并返回结果。
7. 示例用法中,排序前的数组为 `[5, 9, 3, 1, 8, 2, 7, 4, 6]`,排序后的数组为 `[1, 2, 3, 4, 5, 6, 7, 8, 9]`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)