-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort.js
More file actions
89 lines (75 loc) · 1.66 KB
/
quickSort.js
File metadata and controls
89 lines (75 loc) · 1.66 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
import { getDataExtractorApi } from "@hediet/debug-visualizer-data-extraction";
getDataExtractorApi().registerDefaultExtractors();
/*
Visualize this expression:
```ts
hedietDbgVis.markedGrid(
array,
hedietDbgVis.tryEval(["i", "j", "left", "right"])
)
```
*/
// From https://github.com/AvraamMavridis/Algorithms-Data-Structures-in-Typescript/blob/master/algorithms/quickSort.md
const array = [1, 2, 33, 31, 1, 2, 63, 123, 6, 32, 943, 346, 24];
const sorted = quickSort(array, 0, array.length - 1);
console.log(sorted);
function swap(array: Array<number>, i: number, j: number) {
[array[i], array[j]] = [array[j], array[i]];
}
/**
* Split array and swap values
*
* @param {Array<number>} array
* @param {number} [left=0]
* @param {number} [right=array.length - 1]
* @returns {number}
*/
function partition(
array: Array<number>,
left: number = 0,
right: number = array.length - 1
) {
const pivot = Math.floor((right + left) / 2);
const pivotVal = array[pivot];
let i = left;
let j = right;
while (i <= j) {
while (array[i] < pivotVal) {
i++;
}
while (array[j] > pivotVal) {
j--;
}
if (i <= j) {
swap(array, i, j);
i++;
j--;
}
}
return i;
}
/**
* Quicksort implementation
*
* @param {Array<number>} array
* @param {number} [left=0]
* @param {number} [right=array.length - 1]
* @returns {Array<number>}
*/
function quickSort(
array: Array<number>,
left: number = 0,
right: number = array.length - 1
) {
let index;
if (array.length > 1) {
index = partition(array, left, right);
if (left < index - 1) {
quickSort(array, left, index - 1);
}
if (index < right) {
quickSort(array, index, right);
}
}
return array;
}