-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquicksort.js
51 lines (42 loc) · 905 Bytes
/
quicksort.js
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
const swap = (A, i, j) => {
let temp = A[i]
A[i] = A[j]
A[j] = temp
}
//Hoare's Partition
const partition = (a, low, high) => {
let pivot = a[low]
let i = low - 1
let j = high + 1
//(i, j) = (low - 1, high + 1)
while(true){
while(true){
i = i + 1
if(a[i] >= pivot){
break
}
}
while(true){
j = j - 1
if(a[j] <= pivot){
break
}
}
if(i >= j){
return j
}
swap(a, i, j)
}
}
const quicksort = (a, low, high) => {
if(low >= high){
return
}
let pivot = partition(a, low, high)
quicksort(a, low, pivot)
quicksort(a, pivot + 1, high)
}
//put any number in the array
let a = [211,530,60,3,660,390,100,49, 50, 1002, 49, -344]
quicksort(a, 0, a.length - 1)
console.log(a)