-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16. Quick Sort.js
More file actions
38 lines (32 loc) · 1.16 KB
/
16. Quick Sort.js
File metadata and controls
38 lines (32 loc) · 1.16 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
// QUICK SORT
// Escolhe um elemento pivô e joga a esquerda todos os números menores e a direita todos os números maiores e retorna o índice do elemento pivô, repetindo esse processo com todos os elementos, tanto na direita quanto na esquerda.
// Time: best and average: O(n log n) / worst: O(n²)
// Space: O(log n)
function pivot(arr, start = 0, end = arr.length - 1) {
const swap = (arr, idx1, idx2) => {
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
};
// We are assuming the pivot is always the first element
let pivot = arr[start];
let swapIdx = start;
for (let i = start + 1; i <= end; i++) {
if (pivot > arr[i]) {
swapIdx++;
swap(arr, swapIdx, i);
}
}
// Swap the pivot from the start the swapPoint
swap(arr, start, swapIdx);
return swapIdx;
}
function quickSort(arr, left = 0, right = arr.length - 1) {
if (left < right) {
let pivotIndex = pivot(arr, left, right) //3
//left
quickSort(arr, left, pivotIndex - 1);
//right
quickSort(arr, pivotIndex + 1, right);
}
return arr;
}
quickSort([100, -3, 2, 4, 6, 9, 1, 2, 5, 3, 23])