Can someone explain in English how does Non-Recursive merge sort works ?
Thanks
A non-recursive algorithm does the sorting all at once, without calling itself. Bubble-sort is an example of a non-recursive algorithm.
Merge sort involves recursively splitting the array into 2 parts, sorting and finally merging them. A variant of merge sort is called 3-way merge sort where instead of splitting the array into 2 parts we split it into 3 parts. Merge sort recursively breaks down the arrays to subarrays of size half.
This post will sort an integer array using the iterative merge sort algorithm. Merge sort is an efficient sorting algorithm that falls under the Divide and Conquer paradigm and produces a stable sort. It operates by dividing a large array into two smaller subarrays and then recursively sorting the subarrays.
The “Merge Sort” uses a recursive algorithm to achieve its results. The divide-and-conquer algorithm breaks down a big problem into smaller, more manageable pieces that look similar to the initial problem.
Non-recursive merge sort works by considering window sizes of 1,2,4,8,16..2^n over the input array. For each window ('k' in code below), all adjacent pairs of windows are merged into a temporary space, then put back into the array.
Here is my single function, C-based, non-recursive merge sort. Input and output are in 'a'. Temporary storage in 'b'. One day, I'd like to have a version that was in-place:
float a[50000000],b[50000000]; void mergesort (long num) { int rght, wid, rend; int i,j,m,t; for (int k=1; k < num; k *= 2 ) { for (int left=0; left+k < num; left += k*2 ) { rght = left + k; rend = rght + k; if (rend > num) rend = num; m = left; i = left; j = rght; while (i < rght && j < rend) { if (a[i] <= a[j]) { b[m] = a[i]; i++; } else { b[m] = a[j]; j++; } m++; } while (i < rght) { b[m]=a[i]; i++; m++; } while (j < rend) { b[m]=a[j]; j++; m++; } for (m=left; m < rend; m++) { a[m] = b[m]; } } } }
By the way, it is also very easy to prove this is O(n log n). The outer loop over window size grows as power of two, so k has log n iterations. While there are many windows covered by inner loop, together, all windows for a given k exactly cover the input array, so inner loop is O(n). Combining inner and outer loops: O(n)*O(log n) = O(n log n).
Loop through the elements and make every adjacent group of two sorted by swapping the two when necessary.
Now, dealing with groups of two groups (any two, most likely adjacent groups, but you could use the first and last groups) merge them into one group be selecting the lowest valued element from each group repeatedly until all 4 elements are merged into a group of 4. Now, you have nothing but groups of 4 plus a possible remainder. Using a loop around the previous logic, do it all again except this time work in groups of 4. This loop runs until there is only one group.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With