-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.js
More file actions
28 lines (24 loc) · 834 Bytes
/
QuickSort.js
File metadata and controls
28 lines (24 loc) · 834 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
//Swapping array elements via ES6 array destructuring
function swap(arr, x, y) {
[arr[x], arr[y]] = [arr[y], arr[x]];
}
//Pivot function returns the fixed pivot point
function pivot(arr, left = 0, right = arr.length - 1) {
let shift = left;
for (let i = left + 1; i <= right; i++) {
//Move all the small elements on the left side
if (arr[i] < arr[left]) swap(arr, i, ++shift);
}
//Finally swapping the last element with the left
swap(arr, left, shift);
return shift;
}
function quickSort(array, left = 0, right = array.length - 1) {
if (left < right) {
let pivotIndex = pivot(array, left, right);
//Recusrively calling the function to the left of the pivot and to the right of the pivot
quickSort(array, left, pivotIndex - 1);
quickSort(array, pivotIndex + 1, right);
}
return array;
}