1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include<stdio.h>
#include<stdlib.h>
void _mergesort(int *a,int left,int right,int *tmp) {
if(left>=right)
{ return; }
int mid=(left+right)/2;
_mergesort(a,left,mid,tmp); _mergesort(a,mid+1,right,tmp);
int begin1=left,end1=mid; int begin2=mid+1,end2=right; int i=left; while(begin1<=end1&&begin2<=end2) { if(a[begin1]<a[begin2]) { tmp[i++]=a[begin1]; begin1++; } else { tmp[i++]=a[begin2]; begin2++; } }
while(begin1<=end1) { tmp[i++]=a[begin1]; begin1++; } while(begin2<=end2) { tmp[i++]=a[begin2]; begin2++; }
for(int j=left;j<=right;j++) { a[j]=tmp[j]; }
}
void mergesort(int *a,int n) {
int *tmp=(int *)malloc(sizeof(int)*n); if(tmp==NULL) { printf("malloc fail"); return; } _mergesort(a,0,n-1,tmp); free(tmp); tmp=NULL;
}
```c 在这里插入代码片
|