Skip to content

Commit 3f1f39c

Browse files
authored
Merge branch 'master' into master
2 parents f6efb78 + 2c74ced commit 3f1f39c

File tree

1 file changed

+24
-23
lines changed

1 file changed

+24
-23
lines changed

src/algorithms/sorting/merge-sort/MergeSort.js

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -24,36 +24,37 @@ export default class MergeSort extends Sort {
2424
}
2525

2626
mergeSortedArrays(leftArray, rightArray) {
27-
let sortedArray = [];
27+
const sortedArray = [];
2828

29-
// In case if arrays are not of size 1.
30-
while (leftArray.length && rightArray.length) {
31-
let minimumElement = null;
29+
// Use array pointers to exclude old elements after they have been added to the sorted array.
30+
let leftIndex = 0;
31+
let rightIndex = 0;
3232

33-
// Find minimum element of two arrays.
34-
if (this.comparator.lessThanOrEqual(leftArray[0], rightArray[0])) {
35-
minimumElement = leftArray.shift();
33+
while (leftIndex < leftArray.length && rightIndex < rightArray.length) {
34+
let minElement = null;
35+
36+
// Find the minimum element between the left and right array.
37+
if (this.comparator.lessThanOrEqual(leftArray[leftIndex], rightArray[rightIndex])) {
38+
minElement = leftArray[leftIndex];
39+
// Increment index pointer to the right
40+
leftIndex += 1;
3641
} else {
37-
minimumElement = rightArray.shift();
42+
minElement = rightArray[rightIndex];
43+
// Increment index pointer to the right
44+
rightIndex += 1;
3845
}
3946

40-
// Call visiting callback.
41-
this.callbacks.visitingCallback(minimumElement);
42-
43-
// Push the minimum element of two arrays to the sorted array.
44-
sortedArray.push(minimumElement);
45-
}
47+
// Add the minimum element to the sorted array.
48+
sortedArray.push(minElement);
4649

47-
// If one of two array still have elements we need to just concatenate
48-
// this element to the sorted array since it is already sorted.
49-
if (leftArray.length) {
50-
sortedArray = sortedArray.concat(leftArray);
51-
}
52-
53-
if (rightArray.length) {
54-
sortedArray = sortedArray.concat(rightArray);
50+
// Call visiting callback.
51+
this.callbacks.visitingCallback(minElement);
5552
}
5653

57-
return sortedArray;
54+
// There will be elements remaining from either the left OR the right
55+
// Concatenate the remaining elements into the sorted array
56+
return sortedArray
57+
.concat(leftArray.slice(leftIndex))
58+
.concat(rightArray.slice(rightIndex));
5859
}
5960
}

0 commit comments

Comments
 (0)