-
Notifications
You must be signed in to change notification settings - Fork 0
/
quicksort.js
76 lines (69 loc) · 1.38 KB
/
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
function swap(A, i, j)
{
let tmp = A[i]
A[i] = A[j]
A[j] = tmp
}
function partitionLomuto(A, s, e)
{
let idx = s
for (let i = s; i < e; i++) {
if (A[i] < A[e])
swap(A, i, idx++)
}
swap(A, idx, e)
return idx
}
function quickSortLomuto(A, s = 0, e = A.length - 1)
{
if (s < e)
{
let idx = partitionLomuto(A, s, e)
quickSortLomuto(A, s, idx - 1)
quickSortLomuto(A, idx + 1, e)
}
}
function partitionHoare(A, s, e)
{
let p = A[Math.ceil((s + e) / 2)]
while (1)
{
while (A[s] < p)
s++
while (A[e] > p)
e--
if (s >= e)
return s
swap(A, s++, e--)
}
}
function quickSortHoare(A, s = 0, e = A.length - 1)
{
if (s < e)
{
let idx = partitionHoare(A, s, e)
quickSortHoare(A, s, idx - 1)
quickSortHoare(A, idx, e)
}
}
function printArray(A)
{
let s = ""
for (let i = 0; i < A.length; i++) {
s += A[i] + ' '
}
console.log(s)
}
const randomArray = n => Array.from({ length: n }, () => Math.floor(Math.random() * n))
let A = randomArray(50)
printArray(A)
console.time("quickSortLomuto")
quickSortLomuto(A)
console.timeEnd("quickSortLomuto")
printArray(A)
A = randomArray(50)
printArray(A)
console.time("quickSortHoare")
quickSortHoare(A)
console.timeEnd("quickSortHoare")
printArray(A)