# 快速排序
- 时间复杂度(平均):
O(n * log2(n))
- 时间复杂度(最坏):
O(n^2)
- 时间复杂度(最好):
O(n * long2(n))
- 空间复杂度:
O(n * log2(n))
- 不稳定
# 算法
选定一个基点(pivot),将比基点小的数字放在基点左边,比基点大的数据放在基点右边,此时基点为数组中的中间项
再分别对基点左边和基点右边的数组执行上述操作,直到数组剩下一个元素
function quickSort(arr) {
if (arr.length < 2) {
return arr;
}
const pivotIndex = Math.floor(arr.length / 2);
const pivot = arr.splice(pivotIndex, 1);
const left = [];
const right = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] <= pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17