Thanks to visit codestin.com
Credit goes to github.com

Skip to content

mergesort: Use queues to efficiently merge left and right sub-arrays. #83

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

Merged
merged 1 commit into from
Aug 22, 2015

Conversation

lekkas
Copy link
Contributor

@lekkas lekkas commented Aug 22, 2015

First of all, thanks for sharing this repo and for keeping it updated, you are awesome!

After tinkering with mergeSort I noticed that its time performance sharply degrades when we pass a certain input size threshold, just like you have described on your blog post.

It seems that the main culprit is the Array.prototype.shift() method that is used when merging left and right subarrays in mergeSort.merge(). A quick inspection of the Array.prototype.shift() method specification reveals that this operation takes O(N) time. The right.shift() and left.shift() operations are nested within a while loop that runs through all elemens of the subarrays. Therefore we don't have an O(n * logn) algorithm but one that seems to be quadratic.

Instead of arrays, I propose using the working LinkedList data structure to implement a queue ADT and thus spend O(1) instead of O(N) for the same operation. Running a performance test with this approach on an unsorted array of 1M elements dropped the execution time from 8m 39.435s to 0.802s (~650x). More detailed results are here.

Moral of the story: Repeatedly calling Array.prototype.shift() on big data sets can really hurt performance.

@mgechev
Copy link
Owner

mgechev commented Aug 22, 2015

Looks awesome! Thanks for the optimization and the insight notes!

mgechev added a commit that referenced this pull request Aug 22, 2015
mergesort: Use queues to efficiently merge left and right sub-arrays.
@mgechev mgechev merged commit cd56d6a into mgechev:master Aug 22, 2015
@lekkas lekkas deleted the mergesort-with-queues branch August 22, 2015 15:22
@JakeHP
Copy link
Collaborator

JakeHP commented Aug 28, 2015

Nice work @lekkas 👍

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.

3 participants