Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored merge sort to use array pointers instead of .shift() #581

Merged
merged 1 commit into from
Nov 28, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 30 additions & 24 deletions src/algorithms/sorting/merge-sort/MergeSort.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Sort from '../Sort';
import Sort from "../Sort";

export default class MergeSort extends Sort {
sort(originalArray) {
@@ -24,36 +24,42 @@ export default class MergeSort extends Sort {
}

mergeSortedArrays(leftArray, rightArray) {
let sortedArray = [];
const sortedArray = [];

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

// Find minimum element of two arrays.
if (this.comparator.lessThanOrEqual(leftArray[0], rightArray[0])) {
minimumElement = leftArray.shift();
} else {
minimumElement = rightArray.shift();
}
while (leftIndex < leftArray.length && rightIndex < rightArray.length) {
// Find the minimum element between the left and right array
if (
this.comparator.lessThanOrEqual(
leftArray[leftIndex],
rightArray[rightIndex]
)
) {
sortedArray.push(leftArray[leftIndex]);

// Call visiting callback.
this.callbacks.visitingCallback(minimumElement);
// Increment index pointer to the right
leftIndex += 1;

// Push the minimum element of two arrays to the sorted array.
sortedArray.push(minimumElement);
}
// Call visiting callback.
this.callbacks.visitingCallback(leftArray[leftIndex]);
} else {
sortedArray.push(rightArray[rightIndex]);

// If one of two array still have elements we need to just concatenate
// this element to the sorted array since it is already sorted.
if (leftArray.length) {
sortedArray = sortedArray.concat(leftArray);
}
// Increment index pointer to the right
rightIndex += 1;

if (rightArray.length) {
sortedArray = sortedArray.concat(rightArray);
// Call visiting callback.
this.callbacks.visitingCallback(rightArray[rightIndex]);
}
}

return sortedArray;
// There will be one element remaining from either the left OR the right
// Concatenate the remaining element into the sorted array
return sortedArray
.concat(leftArray.slice(leftIndex))
.concat(rightArray.slice(rightIndex));
}
}