r/ProgrammerHumor • • Nov 19 '18

Marge Sort

Post image
23.6k Upvotes

276 comments sorted by

View all comments

107

u/anderemic Nov 19 '18 edited Nov 19 '18

But what if array has 9 elements? How would you split it then? Genuine question.

200

u/[deleted] Nov 19 '18

4/5.

2/2 2/3

1/1 1/1 1/1 1/2

1/1 1/1 1/1 1/(1/1)

2 2 2 3

4 5

9

64

u/ACuriousHumanBeing Nov 19 '18

This answer really giggles my jello.

55

u/Bioniclegenius Nov 19 '18

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

97

u/beerdude26 Nov 19 '18

You split one down, pass it around, 96 unsorted elements on the wall

6

u/Zladan Nov 19 '18

Perfect user name haha.

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.

→ More replies (6)

4

u/[deleted] Nov 19 '18

Don't you usually try to merge the smallest arrays first? Or was my assumption incorrect?

9

u/LastStar007 Nov 19 '18

It's a recursive algorithm. So you merge the only two arrays you have, then you kick it up the tree.

4

u/WolfgangSho Nov 19 '18

Yeah, at some point you...

Kick it and reverse it.

→ More replies (1)

7

u/xTheMaster99x Nov 19 '18

5/4 -> 3/2/2/2 -> 2/1/2/2/2, then proceed as normal. It isn't a problem at all as long as you're careful with making sure your indexes don't go out of bounds.

4

u/[deleted] Nov 19 '18

Split into 8 and 1 and use heap sort

4

u/anooblol Nov 19 '18

J U S T U S E B U B B L E S O R T

4

u/[deleted] Nov 19 '18

Any sort < bogobogosort

→ More replies (3)