void merge(int a[], int m, int b[], int n)
{
int len = m+n-1;
m = m-1;
n = n-1;
int * buffer = calloc(len+1, sizeof(int));
int buffer_length = len+1;
for(int i = 0; i < m+1;i++)
buffer[i] = a[i];
while(m>=0 && n>=0){
if(a[m] < b[n])
buffer[len--] = b[n--];
else
buffer[len--] = a[m--];
}
while(n >= 0){
buffer[len--] = b[n--];
}
for(int i = 0; i < buffer_length;i++)
a[i] = buffer[i];
free(buffer);
}
void merge_sort(int a[], int len)
{
if(len == 0 || len ==1)
return;
int mid = (len-1)/2;
merge_sort(a, mid+1);
merge_sort(a+mid+1,len-mid-1);
merge(a, mid+1, a+mid+1, len-mid-1);
}
网友评论