补充之前博客的几种排序--希尔排序、堆排序、归并排序
希尔排序代码如下:
1 void Shellsort(ElementType A[], int N){ 2 int i, j, Increment; 3 ElementType Tmp; 4 5 for(Increment=N/2; Increment>0; Increment/=2){ 6 for(i=Increment; i<N; i++){ 7 Tmp = A[i]; 8 for(j=i-Increment; j>=0 && A[j]>Tmp; j-=Increment) 9 A[j+Increment] = A[j]; 10 A[j+Increment] = Tmp; 11 } 12 } 13 }
堆排序:
1 #define LeftChild(i) (2*(i)+1) 2 3 void PercDown(Element A[], int i, int N){ 4 int Child; 5 ElementType Tmp; 6 7 for(Tmp=A[i]; LeftChild(i)<N; i=Child){ 8 Child = LeftChild(i); 9 if(Child+1<N && A[Child+1] > A[Child]) 10 Child++; 11 if(Tmp < A[Child]) 12 A[i] = A[Child]; 13 else 14 break; 15 } 16 A[i] = Tmp; 17 } 18 19 void HeapSore(ElementType A[], int N){ 20 int i; 21 for(i=N/2; i>=0; i--){ 22 PercDown(A, i, N); 23 } 24 for(i=N-1; i>0; i--){ 25 swap(&A[0], &A[i]); 26 PercDown(A, 0, i); 27 } 28 }
归并排序实现代码如下:
void MSort(ElementType A[], ElementType TmpArray[], int Left, int Right){ int Center; if(Left < Right){ Center = (Left + Right)/2; MSort(A, TmpArray, Left, Center); MSort(A, TmpArray, Center+1, Right); Merge(A, TmpArray, Left, Center+1, Right); } } void MergeSort(ElementType A[], int N){ ElementType *TmpArray; TmpArray = malloc(N*sizeof(ElementType)); MSort(A, TmpArray, 0, N-1); free(TmpArray); }