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

This commit is contained in:
Austin Theriot 2020-11-28 09:35:08 -06:00 committed by GitHub
parent ed52a8079e
commit 83978e9d2d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,4 +1,4 @@
import Sort from '../Sort'; import Sort from "../Sort";
export default class MergeSort extends Sort { export default class MergeSort extends Sort {
sort(originalArray) { sort(originalArray) {
@ -24,36 +24,42 @@ export default class MergeSort extends Sort {
} }
mergeSortedArrays(leftArray, rightArray) { mergeSortedArrays(leftArray, rightArray) {
let sortedArray = []; const sortedArray = [];
// In case if arrays are not of size 1. // Use array pointers to exclude old elements after they have been added to the sorted array
while (leftArray.length && rightArray.length) { let leftIndex = 0;
let minimumElement = null; let rightIndex = 0;
// Find minimum element of two arrays. while (leftIndex < leftArray.length && rightIndex < rightArray.length) {
if (this.comparator.lessThanOrEqual(leftArray[0], rightArray[0])) { // Find the minimum element between the left and right array
minimumElement = leftArray.shift(); if (
this.comparator.lessThanOrEqual(
leftArray[leftIndex],
rightArray[rightIndex]
)
) {
sortedArray.push(leftArray[leftIndex]);
// Increment index pointer to the right
leftIndex += 1;
// Call visiting callback.
this.callbacks.visitingCallback(leftArray[leftIndex]);
} else { } else {
minimumElement = rightArray.shift(); sortedArray.push(rightArray[rightIndex]);
// Increment index pointer to the right
rightIndex += 1;
// Call visiting callback.
this.callbacks.visitingCallback(rightArray[rightIndex]);
} }
// Call visiting callback.
this.callbacks.visitingCallback(minimumElement);
// Push the minimum element of two arrays to the sorted array.
sortedArray.push(minimumElement);
} }
// If one of two array still have elements we need to just concatenate // There will be one element remaining from either the left OR the right
// this element to the sorted array since it is already sorted. // Concatenate the remaining element into the sorted array
if (leftArray.length) { return sortedArray
sortedArray = sortedArray.concat(leftArray); .concat(leftArray.slice(leftIndex))
} .concat(rightArray.slice(rightIndex));
if (rightArray.length) {
sortedArray = sortedArray.concat(rightArray);
}
return sortedArray;
} }
} }