以下代码符合 CLRS ( Corman, Leiserson, Rivest, Stein — 'Introduction to Algorithms' ) 教科书,该教科书应该进行归并排序。
尽管我知道函数中发生了错误,但我无法确定正在发生的错误mergesort()
。我认为merge()
功能完好。
/* Merge sort as per CLRS */
#include <stdio.h>
#include <stdlib.h>
void merge(int *a,int p,int q,int r){
int n1 = q - p + 1;
int n2 = r - q;
int* l = malloc((n1+1)*sizeof(int));
int* ri = malloc((n2+1)*sizeof(int));
int i,j;
for(i = 0 ; i < n1 ; i++)
l[i] = a[p+i-1];
for(i = 0 ; i < n2 ; i++)
ri[i] = a[q+i];
l[n1] = 9999;
ri[n2] = 9999;
i = 0;
j = 0;
int k;
for ( k = p ; k <= r ; k++){
if( l[i] < ri[j] ){
a[k] = l[i];
i++;
}
else{
a[k] = ri[j];
j++;
}
}
}
void mergeSort(int* a,int p,int r){
if( p < r){
int q = ( p + r ) / 2;
mergeSort(a,p,q);
mergeSort(a,p+1,r);
merge(a,p,q,r);
}
else return;
}
int main(int argc, char* argv[]){
int a[] = {9,21,4,15,1,3};
mergeSort(a,0,5);
int i;
for( i = 0 ; i < 6 ; i++){
printf("%d ",a[i]);
}
return 0;
}