snippetMajor
Can the "divide" step in a merge sort be avoided?
Viewed 0 times
dividecanthemergeavoidedstepsort
Problem
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?
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?
Solution
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
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 :-)
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 :-)
Code Snippets
/*
* Note: array is now split into [0..n) and [n..N)
*/Context
StackExchange Computer Science Q#79942, answer score: 29
Revisions (0)
No revisions yet.