-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquick-sort.js
More file actions
41 lines (38 loc) · 830 Bytes
/
quick-sort.js
File metadata and controls
41 lines (38 loc) · 830 Bytes
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
const swap = (array, i, j) => {
let temp = array[i];
array[i] = array[j];
array[j] = temp;
};
const partiton = (array, low, high) => {
const pivotIndex = high;
const pivotElement = array[pivotIndex];
let i = low,
j = pivotIndex - 1;
while (true) {
while (array[i] < pivotElement) {
i++;
}
while (array[j] >= pivotElement) {
j--;
}
if (i > j) {
break;
} else {
swap(array, i, j);
}
}
swap(array, i, pivotIndex);
return i;
};
const quickSort = (array, low, high) => {
if (low > high) {
return;
} else {
const pivotIndex = partiton(array, low, high);
quickSort(array, low, pivotIndex - 1);
quickSort(array, pivotIndex + 1, high);
}
};
const array = [9, 5, 2, 6, 1, 11, 3];
quickSort(array, 0, array.length - 1);
console.log(array);