forked from Eished/JavaScript_notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort.js
More file actions
54 lines (48 loc) · 1.34 KB
/
Copy pathquickSort.js
File metadata and controls
54 lines (48 loc) · 1.34 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 partition(arr, start, end) {
// 以最后一个元素为基准
const pivotValue = arr[end]
let pivotIndex = start
for (let i = start; i < end; i++) {
if (arr[i] < pivotValue) {
// 交换元素
;[arr[i], arr[pivotIndex]] = [arr[pivotIndex], arr[i]]
// 移动到下一个元素
pivotIndex++
}
}
// 把基准值放在中间
;[arr[pivotIndex], arr[end]] = [arr[end], arr[pivotIndex]]
return pivotIndex
}
function quickSortRecursive(arr, start, end) {
// 终止条件
if (start >= end) {
return
}
// 返回 pivotIndex
let index = partition(arr, start, end)
// 将相同的逻辑递归地用于左右子数组
quickSortRecursive(arr, start, index - 1)
quickSortRecursive(arr, index + 1, end)
}
const array = [7, -2, 4, 7, 1, 3, 6, 5, 3, 0, -4, 2]
// quickSortRecursive(array, 0, array.length - 1)
// console.log(array)
const myQuickSort = (arr) => {
if (arr.length <= 1) {
return arr
}
const pivotIndex = Math.floor(arr.length / 2)
const pivot = arr.splice(pivotIndex, 1)[0]
const left = []
const right = []
arr.forEach((num) => {
if (num < pivot) {
left.push(num)
} else {
right.push(num)
}
})
return myQuickSort(left).concat([pivot], myQuickSort(right))
}
// console.log(myQuickSort(array))