Conceptually, merge sort works as follows :
If the list to be sorted is longer than one item:
Mergesort is so sequential that it's practical to run it on tapes if you have four tape drives. It works as follows:
For the same reason it is also very useful for sorting data on disk that is too big to fit into primary memory.
This might seem to be of historical interest only, but on modern computers, locality of reference is of paramount importance in software optimization, because we have deep memory hierarchies. This might change if fast memory becomes very cheap again, or if exotic architectures like the Tera MTA become commonplace.
Here is some C code that does merge sort. It assumes that two arrays, v1 and v2 have been allocated to be of size n/2; they will be used for the merging operation: (from PD [lecture notes])
void merge (float [], int, int, int);
/* sort the (sub)array v from start to end */
void merge_sort (float v[], int start, int end) { int middle; /* the middle of the subarray */
/* no elements to sort */ if (start == end) return;
/* one element; already sorted! */ if (start == end - 1) return;
/* find the middle of the array, splitting it into two subarrays */ middle = (start + end) / 2;
/* sort the subarray from start..middle */ merge_sort (v, start, middle);
/* sort the subarray from middle..end */ merge_sort (v, middle, end);
/* merge the two sorted halves */ merge (v, start, middle, end); }
/* merge the subarray v[start..middle] with v[middle..end], placing the
* result back into v. */void merge (float v[], int start, int middle, int end) { int v1_n, v2_n, v1_index, v2_index, i;/* number of elements in first subarray */ v1_n = middle - start;
/* number of elements in second subarray */ v2_n = end - middle;
/* fill v1 and v2 with the elements of the first and second * subarrays, respectively */ for (i=0; i
/* v1_index and v2_index will index into v1 and v2, respectively... */ v1_index = 0; v2_index = 0; /* ... as we pick elements from one or the other to place back * into v */ for (i=0; (v1_index < v1_n) && (v2_index < v2_n); i++) {
/* current v1 element less than current v2 element? */ if (v1[v1_index] <= v2[v2_index])
/* if so, this element belong as next in v */ v[start + i] = v1[v1_index++]; else /* otherwise, the element from v2 belongs there */ v[start + i] = v2[v2_index++]; } /* clean up; either v1 or v2 may have stuff left in it */
for (; v1_index < v1_n; i++) v[start + i] = v1[v1_index++]; for (; v2_index < v2_n; i++) v[start + i] = v2[v2_index++]; }