Merge Sort is an efficient method for sorting elements in an array, based on the following idea: if the first half of the array is sorted and the second half is also sorted, by merging these two halves, the entire array will be sorted.
Merge Sort is a typical example of a divide and conquer algorithm: it sorts a sequence delimited by indices st and dr:
In the following sequence, the tmp array is considered globally declared, of the same size as v:
void MergeSort(int v[], int st, int dr)
{
if(st < dr)
{
int m = (st + dr) / 2;
MergeSort(v, st , m);
MergeSort(v, m + 1 , dr);
// Merging
int i = st, j = m + 1, k = 0;
while( i <= m && j <= dr )
if( v[i] < v[j])
tmp[++k] = v[i++];
else
tmp[++k] = v[j++];
while(i <= m)
tmp[++k] = v[i++];
while(j <= dr)
tmp[++k] = v[j++];
for(i = st , j = 1 ; i <= dr ; i++ , j++)
v[i] = tmp[j];
}
}