-
Notifications
You must be signed in to change notification settings - Fork 154
/
quick-sort.js
53 lines (44 loc) · 855 Bytes
/
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
/**
* Quick Sort
*
* Lomuto's partition schema
*/
const swap = (nums, i, j) => ([nums[i], nums[j]] = [nums[j], nums[i]]);
/**
* Lomuto's partition scheme
*
* @param {number[]} nums
* @param {number} lo
* @param {number} hi
*/
const partition = (nums, lo, hi) => {
for (var i = lo, j = lo; j < hi; j++) {
if (nums[j] <= nums[hi]) {
swap(nums, i++, j);
}
}
swap(nums, i, j);
return i;
};
/**
* Quick sort helper - Returns sorted nums
*
* @param {number[]} nums
* @param {number} lo
* @param {number} hi
*/
const sort = (nums, lo, hi) => {
if (lo >= hi) {
return;
}
const pivot = partition(nums, lo, hi);
sort(nums, lo, pivot - 1);
sort(nums, pivot + 1, hi);
};
/**
* Quick sort
*
* @param {number[]} nums
*/
const quickSort = nums => sort(nums, 0, nums.length - 1);
export default quickSort;