-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathquickSort.js
More file actions
35 lines (24 loc) · 706 Bytes
/
quickSort.js
File metadata and controls
35 lines (24 loc) · 706 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
const arr = [4, 16, 7, 3, 6, 1, 0, 5, 7, 12, 2];
function quickSort(arr, start = 0, end = arr.length - 1){
if (start >= end) return;
const pivot = partition(arr, start, end);
quickSort(arr, start, pivot - 1);
quickSort(arr, pivot + 1, end);
return arr;
}
function partition(arr, start, end) {
const pivot = end;
let lastSwapIdx = start;
for (let idx = start; idx <= end; idx++) {
if (arr[idx] < arr[pivot]) {
swap(arr, idx, lastSwapIdx);
lastSwapIdx++;
}
}
swap(arr, lastSwapIdx, pivot);
return lastSwapIdx;
}
function swap(arr, a ,b) {
[arr[a], arr[b]] = [arr[b], arr[a]];
}
console.log(quickSort(arr))