Refactored merge sort to use array pointers instead of .shift() #581
+30
−24
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The previous implementation of merge sort used the array.shift() method to merge elements from leftArray and rightArray into the sorted array. This is a bad practice, because JavaScript's implementation of the Array.prototype.shift() method is, at worst, O(n) runtime complexity, where n is the length of the array being sorted (in order to move n elements of an array over by 1, all n elements of the array must typically be touched).
To work around this, I refactored merge sort to use array pointers instead. Now, after an element has been added to the sorted array, rather than delete it from the old array and shift the entire old array over, the array index pointer is just incremented to the right by one to avoid the old element. This will always require O(1) runtime complexity, which is a significant performance boost.
I also added two simple concat() statements to the returned sortedArray value, because the length of the left and right arrays can no longer be used to determine if an element is still "dangling" (needing to be added to the sorted array).
All tests passed after my changes.
Quick Stack Overflow info on JavaScript array method runtime complexities