-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (39 loc) · 935 Bytes
/
index.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
let arrayToSort = Array(1000000).fill().map(() => Math.round(Math.random() * 1000000))
function quicksort(array, left, right) {
left = left || 0
right = right || array.length - 1
let pivot = partition(array, left, right)
if (left < pivot - 1) {
quicksort(array, left, pivot - 1)
}
if (right > pivot) {
quicksort(array, pivot, right)
}
return array
}
// Hoare partition scheme
function partition(array, left, right) {
let pivot = Math.floor((left + right) / 2)
while (left <= right) {
while (array[left] < array[pivot]) {
left++
}
while (array[right] > array[pivot]) {
right--
}
if (left <= right) {
swap(array, left, right)
left++
right--
}
}
return left
}
function swap(array, i, j) {
let tmp = array[i]
array[i] = array[j]
array[j] = tmp
}
console.time('quicksort')
console.log(quicksort(arrayToSort))
console.timeEnd('quicksort')