-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathquickSort.js
More file actions
54 lines (47 loc) · 1.08 KB
/
Copy pathquickSort.js
File metadata and controls
54 lines (47 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* 非递归实现快速排序
*/
function quickSort(data, low, high) {
console.log(data, low, high)
const pivot = partition(data, low, high)
const result = []
if (pivot + 1 < high) {
result.push(pivot + 1, high)
}
else if (pivot > low + 1) {
result.push(low, pivot - 1)
}
// 数组不为空
while (result.length > 0) {
const tempHigh = result.pop()
const tempLow = result.pop()
if (tempLow >= tempHigh) {
break
}
const tempPivot = partition(data, tempLow, tempHigh)
if (tempPivot + 1 < high) {
result.push(tempPivot + 1, tempHigh)
}
else if (tempPivot - 1 > low) {
result.push(tempLow, tempPivot - 1)
}
}
return data
}
/**
* 严版获取快排pivot
*/
function partition(data, low, high) {
const pivot = data[low]
while (low < high) {
// 高位
while (low < high && pivot <= data[high]) --high
data[low] = data[high]
// 低位
while (low < high && pivot >= data[low]) ++low
data[high] = data[low]
}
data[low] = pivot
return low
}
console.log(quickSort([1, 8, 9, 2], 0, 3))