-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathquick-sort.js
59 lines (45 loc) · 1.29 KB
/
quick-sort.js
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
const 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++;
// let temp = arr[i];
// arr[i] = pivot;
// pivot = temp;
swap(arr, swapIdx, i);
}
}
// Swap the pivot from the start the swapPoint
swap(arr, start, swapIdx);
return swapIdx;
}
let totalIterations = 0;
const quickSort = (arr, left = 0, right = arr.length - 1) => {
totalIterations++;
if (left < right) {
let pivotIndex = pivot(arr, left, right) //3
//left
quickSort(arr, left, pivotIndex - 1);
//right
quickSort(arr, pivotIndex + 1, right);
}
return arr;
}
console.log(quickSort([100, -3, 2, 4, 6, 9, 1, 2, 5, 3, 23]))
console.log('totalIterations', totalIterations);
totalIterations = 0;
console.log(quickSort([10, 53, 0, 34, 390, -2, 45]));
console.log('totalIterations', totalIterations);
// [4,6,9,1,2,5,3]
// [3,2,1,4,6,9,5]
// 4
// 3,2,1 6,9,5
// 3 6
// 2,1 5 9
// 2
// 1