Non-recursive merge sort considering window sizes 1,2,4,8,16..2 ^ n over the input array. For each window (“k” in the code below), all adjacent pairs of windows are merged into temporary space and then returned to the array.
Here is my only function, C-based, non-recursive merge sort. Entrance and exit are in 'a'. Temporary storage in 'b'. One day, I would 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 that it is O (n log n). The outer loop over the window size grows as the power of two, so k has log n iterations. While there are many windows covered by the inner loop, together, all the windows for a given k exactly cover the input array, so the inner loop is O (n). Combining internal and external loops: O (n) * O (log n) = O (n log n).
Rama Hoetzlein Jul 30 '13 at 20:50 2013-07-30 20:50
source share