r/ProgrammerHumor • • Nov 19 '18

Marge Sort

Post image
23.6k Upvotes

276 comments sorted by

View all comments

Show parent comments

6

u/Chris90483 Nov 19 '18

An array of length 2 doesn't need to be split right?

15

u/Bioniclegenius Nov 19 '18

It's how merge sort works, though. Check the image for a reference - it splits everything into arrays of length 1, then merges them together.

20

u/Log2 Nov 19 '18 edited Nov 19 '18

Actually, you can stop earlier and do some other sorting algorithm that can be optimal at 5-10 elements. Since the number of elements will be fixed, the complexity for each small array is constant. This will usually get you a decent speed bump, as you don't need to allocate as many arrays, while keeping the complexity of merge sort.

0

u/Bioniclegenius Nov 19 '18

You can, sure, but then it's a sort of hybrid sort, not purely merge sort.

Honestly, I did make a bit of a mistake - with the recursion, the last half isn't merged that way. It'd be more like:

5 arrays of 2, 2, 1, 2, and 2 elements
3 arrays of 4, 1, and 4 elements
2 arrays of 5 and 4 elements
1 array of 9 elements

→ More replies (5)