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

Conversation

austintheriot
Copy link
Contributor

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

@trekhleb trekhleb changed the base branch from master to merge November 28, 2020 15:34
@trekhleb
Copy link
Owner

@austintheriot , thanks for the contribution!

@trekhleb trekhleb merged commit 83978e9 into trekhleb:merge Nov 28, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants