-
Notifications
You must be signed in to change notification settings - Fork 154
/
merge-sort.js
63 lines (53 loc) · 969 Bytes
/
merge-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
56
57
58
59
60
61
62
63
/**
* Merge Sort
*/
/**
* Merge [lo...mid] and [mid + 1...hi]
*
* @param {number[]} nums
* @param {number} lo
* @param {number} mid
* @param {number} hi
*/
const merge = (nums, lo, mid, hi) => {
let i = lo;
let j = mid + 1;
let k = lo;
const copy = nums.slice();
while (i <= mid && j <= hi) {
if (copy[i] < copy[j]) {
nums[k++] = copy[i++];
} else {
nums[k++] = copy[j++];
}
}
while (i <= mid) {
nums[k++] = copy[i++];
}
while (j <= hi) {
nums[k++] = copy[j++];
}
};
/**
* Merge sort helper
*
* @param {number[]} nums
* @param {number} lo
* @param {number} hi
*/
const sort = (nums, lo, hi) => {
if (lo >= hi) {
return;
}
const mid = lo + Math.floor((hi - lo) / 2);
sort(nums, lo, mid);
sort(nums, mid + 1, hi);
merge(nums, lo, mid, hi);
};
/**
* Merge Sort
*
* @param {number[]} nums
*/
const mergeSort = nums => sort(nums, 0, nums.length - 1);
export default mergeSort;