-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort.js
More file actions
31 lines (23 loc) · 714 Bytes
/
quickSort.js
File metadata and controls
31 lines (23 loc) · 714 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
const swap = (arr, idx1, idx2) => {
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]]
}
const pivot = (arr, pivotIndex = 0, endIndex = arr.length - 1) => {
let swapIndex = pivotIndex;
for (let i = pivotIndex + 1; i <= endIndex; i++){
if(arr[i] < arr[pivotIndex]) {
swapIndex++
swap(arr, swapIndex, i)
}
}
swap(arr, pivotIndex, swapIndex )
return swapIndex;
}
const quickSort = (arr, left = 0, right = arr.length - 1) => {
if(left < right) {
let pivotIndex = pivot(arr, left, right)
quickSort(arr, left, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, right);
}
return arr;
}
console.log(quickSort([5, 9, 7, 4, 2 , 3]))