#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
void
wrt(int key[], int sz);
void
mergesort(int key[], int n);
void
merge(int a[], int b[], int c[], int m, int n);
void merge(int a[],int b[],int c[], int m,int n)
{
int i=0,j=0,k=0;
while(i<m && j<n)
if(a[i] < b[i])
c[k++]=a[i++];
else
c[k++]=b[j++];
while (i<m)
c[k++]=a[i++];
while (j<n)
c[k++] = b[j++];
}
void mergesort(int key[],int n)
{
int j,k,m,*w;
w =(int*) calloc(n, sizeof(int));
for(m = 1; m < n; m *= 2)
{
if (n < m)
{
printf("ERROR:Array size not apower of 2 - bye!\n");
exit(1);
}
assert(w != NULL);
for (k = 1; k < n; k *=2)
{
for(j = 0; j < n - k; j += 2*k)
merge(key + j, key + j + k, w + j, k, k);
for (j = 0; j < n; ++j)
key[j] = w[j];
}
}
free(w);
}
void wrt(int key[], int sz)
{
int
i;
for (i = 0; i <sz; ++i)
printf("%4d%s",key[i],((i < sz - 1) ? "" : "\n"));
}
int main(void)
{
int sz,key[]={ 4, 3, 6, 67,5,8,7,9};
sz=sizeof(key) / sizeof(int);
printf("Before mergesort:\n");
wrt(key,sz);
mergesort(key,sz);
printf("After mergesort:\n");
wrt(key,sz);
return 0;
}