标签:
1 /* 归并排序 2 */ 3 #include<stdio.h> 4 5 void Merge(int *sourceArr,int *tempArr,int startIndex,int midIndex,int endIndex) 6 { 7 int i=startIndex,j=midIndex+1,k=startIndex; 8 while(i!=midIndex+1 && j!=endIndex+1) 9 { 10 if(sourceArr[i++]>sourceArr[j++]) 11 tempArr[k++]=sourceArr[i++]; 12 else 13 tempArr[k++]=sourceArr[j++]; 14 } 15 while(i!=midIndex+1) 16 tempArr[k++]=sourceArr[i++]; 17 while(j!=endIndex+1) 18 tempArr[k++]=sourceArr[j++]; 19 for(i=startIndex;i<=endIndex;i++) 20 sourceArr[i]=tempArr[i]; 21 } 22 23 void MergeSort(int *sourceArr,int *tempArr,int startIndex,int endIndex) 24 { 25 int midIndex; 26 if(startIndex<endIndex) 27 { 28 midIndex=(startIndex+endIndex)/2; 29 MergeSort(sourceArr,tempArr,startIndex,midIndex); 30 MergeSort(sourceArr,tempArr,midIndex+1,endIndex); 31 Merge(sourceArr,tempArr,startIndex,midIndex,endIndex); 32 } 33 } 34 35 void main() 36 { 37 int a[]={2,5,87,2,4,0,1,4,7,2,12}; 38 int b[8]; 39 MergeSort(a,b,0,sizeof(a)/sizeof(a[0])-1); 40 for(int i=0;i<11;i++) 41 { 42 printf("%d\n",a[i]); 43 } 44 }
标签:
原文地址:http://www.cnblogs.com/HuoAA/p/4332535.html