-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickSort.js
78 lines (59 loc) · 2.14 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
77
78
async function quickSortAlgo(integerArray, low, high, barArray) {
if (low < high) {
const pivotIndex = await partition(integerArray, low, high, barArray);
await Promise.all([
quickSortAlgo(integerArray, low, pivotIndex - 1, barArray),
quickSortAlgo(integerArray, pivotIndex + 1, high, barArray)
]);
}
if (low >= 0 && high < integerArray.length) {
for (let i = low; i <= high; i++) {
barArray[i].classList.remove('rightArray');
barArray[i].classList.remove('leftArray');
barArray[i].classList.add('sortedBar');
}
}
}
async function partition(integerArray, low, high, barArray) {
// select the pivot value
const pivot = integerArray[high];
barArray[high].classList.remove('rightArray');
barArray[high].classList.remove('leftArray');
barArray[high].classList.add('pivotBar');
// reset the section of the array thats about to be partitioned to unsorted
for (let a = low; a < high; a++) {
barArray[a].classList.remove('leftArray');
barArray[a].classList.remove('rightArray');
}
let i = low - 1;
for (let j = low; j < high; j++) {
barArray[j].classList.remove('rightArray');
barArray[j].classList.remove('leftArray');
barArray[j].classList.add('activeBar');
await new Promise(resolve => setTimeout(resolve, interval));
// check for pause
if (pauseButton) {
await waitForUnPause();
pauseButton = false;
}
if (integerArray[j] < pivot) {
i++;
// swap
swapInts(i, j);
swapBars(i, j);
barArray[i].classList.remove('rightArray');
barArray[i].classList.add('leftArray');
}
barArray[j].classList.remove('activeBar');
if (j != i) {
barArray[j].classList.add('rightArray');
}
}
barArray[high].classList.remove('pivotBar');
// swap
swapInts(i + 1, high);
swapBars(i + 1, high);
barArray[i + 1].classList.remove('rightArray');
barArray[i + 1].classList.add('sortedBar');
return i + 1;
}