1 //插入排序 2 int a[n]; 3 for(int i=2;i<=n;i++) 4 { 5 int s=a[i]; 6 int j=i-1; 7 while(j&&a[j]>a[i]) 8 { 9 a[j+1]=a[j]; 10 j--; 11 } 12 a[j+1]=s; 13 } 14 15 16 int part(int a[],int low,int high) 17 { 18 int tmp=a[low]; 19 while(low<high) 20 { 21 while(low<high&&a[high]>=tmp) 22 high--; 23 if(low<high) 24 { 25 a[low]=a[high]; 26 low++; 27 } 28 while(low<high&&a[low]<=tmp) 29 low++; 30 if(low<high) 31 { 32 a[high]=a[low]; 33 high--; 34 } 35 } 36 a[low]=tmp; 37 return low; 38 } 39 40 void quick_sort(int a[],int low,int high) 41 { 42 int mid; 43 if(low<high) 44 { 45 mid=(low+high)/2; 46 mid=part(a,low,high); 47 quick_sort(a,low,mid-1); 48 quick_sort(a,mid+1,high); 49 } 50 return ; 51 } 52 53 /************归并************/ 54 void merge(int a[],int low,int high) 55 { 56 int b1=low; 57 int mid=(low+high)/2; 58 int b2=mid+1; 59 int len=high-low+1; 60 int *b,k=0; 61 b=(int *)malloc(len*sizeof(int)); 62 while(b1<=mid&&b2<=high) 63 { 64 if(a[b1]<=a[b2]) 65 b[k++]=a[b1++]; 66 else 67 b[k++]=a[b2++]; 68 } 69 while(b1<=mid) 70 b[k++]=a[b1++]; 71 while(b2<=high) 72 b[k++]=a[b2++]; 73 for(int i=0;i<len;i++) 74 a[low++]=b[i]; 75 free(b); 76 } 77 78 void merge_sort(int a[],int low,int high) 79 { 80 int mid=(low+high)/2; 81 if(low<high) 82 { 83 merge_sort(a,low,mid); 84 merge_sort(a,mid+1,high); 85 merge(a,low,high); 86 } 87 return ; 88 }
时间: 2024-10-11 07:52:30