-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort.js
More file actions
58 lines (42 loc) · 1.23 KB
/
Copy pathquickSort.js
File metadata and controls
58 lines (42 loc) · 1.23 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
55
56
57
let sortedarr = []
const swap = (arr, i, j) => {
const temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
const partition = (dupbars, low, high) => {
const pivot = low
let j = low
for(let i = low + 1;i<=high;i++){
sortedarr.push([i, pivot, null, null])
if(dupbars[i] < dupbars[pivot]){
j += 1
swap(dupbars, i, j)
sortedarr.push([i, j, dupbars.slice(), null])
}
}
swap(dupbars, pivot, j)
sortedarr.push([pivot, j, dupbars.slice(), null])
sortedarr.push([null, null, null, j])
return j
}
const quickSortHelper = (dupbars, low, high) => {
if(low >= high) {
if(low === high) sortedarr.push([null, null, null, low])
return
}
const pivot = low + Math.floor(Math.random() * (high - low))
swap(dupbars, low, pivot)
sortedarr.push([low, pivot, dupbars.slice(), null])
const mid = partition(dupbars, low, high)
quickSortHelper(dupbars, low, mid - 1)
quickSortHelper(dupbars, mid + 1, high)
return
}
const quickSort = (blocks) => {
const dupbars = blocks.slice()
sortedarr = []
quickSortHelper(dupbars, 0, dupbars.length - 1)
return sortedarr
}
export default quickSort