13

Merge sort

So merge sort is a divide and conquer algorithm. While I was looking at the above diagram, I was thinking if it was possible to basically bypass all the divide steps.

If you iterated over the original array while jumping by two, you could get the elements at at index i and i+1 and put them into their own sorted arrays. Once you have all these sub-arrays ([7,14], [3,12], [9,11] and [2,6] as shown in the diagram), you could simply proceed with the normal merge routine to get a sorted array.

Is iterating through the array and immediately generating the required sub-arrays less efficient than performing the divide steps in their entirety?

Raphael
  • 73,212
  • 30
  • 182
  • 400
Jimmy_Rustle
  • 245
  • 3
  • 6

2 Answers2

29

The confusion arises from difference between the conceptual description of the algorithm, and its implementation.

Logically merge sort is described as splitting up the array into smaller arrays, and then merging them back together. However, "splitting the array" doesn't imply "creating an entirely new array in memory", or anything like that - it could be implemented in code as

/*
 * Note: array is now split into  [0..n) and [n..N)
 */

i.e. no actual work takes place, and the "splitting" is purely conceptual. So what you suggest certainly does work, but logically you're still "splitting" the arrays - you just don't need any work from the computer to do so :-)

psmears
  • 481
  • 3
  • 8
11

I guess what you mean is the bottom-up implementation. In the bottom up implementation you start from single cell elements an move upward by merging elements into larger sorted lists/arrays. Just reverse the arrows in your figure above starting from the middle array, i.e., one-element arrays.

Also, you may want to optimize the merge sort by dividing arrays until they reach some constant size, after which you simply sort them using for example insertion sort.

Otherwise, sorting without splitting array is not possible. In fact the gist of the Merge sort is dividing and sorting subarrays, i.e., divide-and-conquer.

fade2black
  • 9,905
  • 2
  • 26
  • 36