归并排序
1 #include<stdio.h> 2 void MERGE(int *A,int p,int q,int r){ 3 int i,j,k; 4 int *B=malloc((r-p+1)*sizeof(int)); 5 i=p;j=q+1;k=0; 6 while(i<=q&&j<=r){ 7 if(A[i]<A[j]){ 8 B[k]=A[i]; 9 i++; 10 } 11 else{ 12 B[k]=A[j]; 13 j++; 14 } 15 k++; 16 } 17 while(i<=q){B[k]=A[i];i++;k++;} 18 while(j<=r){B[k]=A[j];j++;k++;} 19 for(i=p,k=0;i<=r;i++,k++){ 20 A[i]=B[k]; 21 } 23 } 24 void MERGE_SORTUP(A,p,r){ 25 int q; 26 if(p<r){ 27 q=(p+r)/2; 28 MERGE_SORTUP(A,p,q); 29 MERGE_SORTUP(A,q+1,r); 30 MERGE(A,p,q,r); 31 } 32 } 33 34 int main(){ 35 int A[]={19,28,73,65,53,14,34,27,1,0}; 36 int length=sizeof(A)/sizeof(int); 37 int i; 38 MERGE_SORTUP(A,0,0+length-1); 39 for(i=0;i<length;i++) 40 printf("%d\t",A[i]); 41 }
结果: