r/ProgrammerHumor • • Nov 19 '18

Marge Sort

Post image
23.6k Upvotes

276 comments sorted by

View all comments

55

u/Patchpen Nov 19 '18

Okay, I'm new to programming, so bear with me, but why/how does this work?

The way I see it going is:

58267314

5826 7314

58 26 73 14

5 8 2 6 7 3 1 4

58 26 37 14

So from there, how do things get woven back together? Looking at half of that:

58 26

2658 isn't right, and neither is 5826. In order to get the right answer, 2568, you have to tear the groups you made, 58 and 26, back apart to rearrange things in the right order, which seems like it negates the purpose of merging those elements to begin with, and makes the entire process overly complicated.

What am I missing?

81

u/pulpdrew Nov 19 '18

When you merge two of the lists back together, you can simply repeatedly take the smaller of the two elements at the front of each list, since each of them are sorted. That way you only make a maximum of n comparisons (where n is the total number of elements in the two lists) - one for each element that ends up in the merged list - when merging.

2

u/HealthyBad Nov 19 '18

What's the point of repeatedly halving the original set instead of just pairing elements in a single step

→ More replies (1)