Skip to content

Commit 3274b4b

Browse files
committed
Improve merge sort implementation
1 parent 7df9bd1 commit 3274b4b

File tree

1 file changed

+27
-19
lines changed

1 file changed

+27
-19
lines changed

src/algorithms/sorting/merge_sort.js

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,27 @@
11
const Comparator = require('../../util/comparator');
22

3-
const merge = (a, b, comparator) => {
4-
let i = 0;
5-
let j = 0;
6-
const result = [];
3+
const merge = (wp, arr, left, middle, right, comparator) => {
4+
let i = left;
5+
let j = middle + 1;
6+
let k = i;
77

8-
while (i < a.length && j < b.length) {
9-
result.push(comparator.lessThan(a[i], b[j]) ? a[i++] : b[j++]);
8+
while (i <= middle && j <= right) {
9+
if (comparator.lessThan(arr[i], arr[j])) {
10+
wp[k++] = arr[i++];
11+
} else {
12+
wp[k++] = arr[j++];
13+
}
1014
}
1115

12-
// Concats the elements from the sub-array
13-
// that has not been included yet
14-
return result.concat(i < a.length ? a.slice(i) : b.slice(j));
16+
while (i <= middle) {
17+
wp[k++] = arr[i++];
18+
}
19+
while (j <= right) {
20+
wp[k++] = arr[j++];
21+
}
22+
while (left <= right) {
23+
arr[left] = wp[left++];
24+
}
1525
};
1626

1727
/**
@@ -20,17 +30,15 @@ const merge = (a, b, comparator) => {
2030
*/
2131
const mergeSortInit = (a, compareFn) => {
2232
const comparator = new Comparator(compareFn);
23-
24-
return (function mergeSort(a) {
25-
if (a.length > 1) {
26-
const middle = a.length >> 1;
27-
const left = mergeSort(a.slice(0, middle));
28-
const right = mergeSort(a.slice(middle));
29-
a = merge(left, right, comparator);
33+
(function mergeSort(wp, arr, left, right) {
34+
if (right - left >= 1) {
35+
const middle = Math.floor((left+right)/2);
36+
mergeSort(wp, arr, left, middle);
37+
mergeSort(wp, arr, middle + 1, right);
38+
merge(wp, arr, left, middle, right, comparator);
3039
}
31-
32-
return a;
33-
})(a);
40+
})([], a, 0, a.length - 1);
41+
return a;
3442
};
3543

3644
module.exports = mergeSortInit;

0 commit comments

Comments
 (0)