-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort.ts
More file actions
103 lines (88 loc) · 1.75 KB
/
Copy pathquickSort.ts
File metadata and controls
103 lines (88 loc) · 1.75 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { pause } from '../utils/pause';
import { AlgorithmArgs, AlgorithmFunction } from './types';
type PartitionArg = {
array: number[];
start: number;
end: number;
} & AlgorithmArgs;
const partition = async ({
array,
start,
end,
updateUI,
history,
player,
}: PartitionArg): Promise<number> => {
const pivotElement = array[end];
let partitionIndex = start;
for (let i = start; i < end; i++) {
updateUI(array, { pivotIndex: end });
if (array[i] < pivotElement) {
updateUI(array, {
activeIndex: i,
compareIndex: partitionIndex,
});
[array[i], array[partitionIndex]] = [array[partitionIndex], array[i]];
await pause({ history, player });
partitionIndex++;
}
}
[array[partitionIndex], array[end]] = [array[end], array[partitionIndex]];
updateUI(array);
return partitionIndex;
};
const quickSortRecursive = async ({
array,
start,
end,
updateUI,
history,
player,
}: PartitionArg): Promise<void> => {
if (start >= end) {
return;
}
await pause({ history, player });
const index = await partition({
array,
start,
end,
updateUI,
history,
player,
});
updateUI(array, { sortedIndices: [index] });
await quickSortRecursive({
array,
start,
end: index - 1,
updateUI,
history,
player,
});
await quickSortRecursive({
array,
start: index + 1,
end,
updateUI,
history,
player,
});
};
export const quickSort: AlgorithmFunction = async ({
array,
updateUI,
history,
player,
}) => {
await quickSortRecursive({
array,
start: 0,
end: array.length - 1,
updateUI,
history,
player,
});
updateUI(array, { sortedIndices: array.map((_, idx) => idx) });
return array;
};