是根据 “数据结构和算法分析”里面的算法写的。
代码如下:
extern void QSort(int A[], int left, int right); extern void InsertionSort(int A[], int size); extern void Swap(int *a, int *b); void QuickSort(int A[], int N) { QSort(A, 0, N - 1); } int Median3(int array[], int left, int right) { int center = (left + right ) / 2; if(array[left] > array[center]) { Swap(&array[left], &array[center]); } if(array[left] > array[right]) { Swap(&array[left], &array[right]); } if(array[center] > array[right]) { Swap(&array[center], &array[right]); } Swap(&array[center], &array[right - 1]); return array[right - 1]; } #define CUTOFF 3 void QSort(int A[], int left, int right) { int i, j; int pivot; if(left + CUTOFF <= right) { pivot = Median3(A, left, right); #if 1 i = left; j = right - 1; #else i = left + 1; j = right - 2; #endif for(;;) { #if 1 while(A[++i] < pivot) {} while(A[--j] > pivot) {} #else while(A[i] < pivot) i++; while(A[j] > pivot) j--; #endif if(i < j) { Swap(&A[i], &A[j]); } else { break; } } Swap(&A[i], &A[right - 1]); QSort(A, left, i - 1); QSort(A, i + 1, right); } else { InsertionSort(A + left, right -left + 1); } }
void InsertionSort(int A[], int N) { int j, p; int tmp; for(p = 1; p < N; p++) { tmp = A[p]; for(j = p; j > 0 && A[j - 1] > tmp; j--) { A[j] = A[j - 1]; } A[j] = tmp; } }
swap函数:
void Swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; }
void QSort(int A[], int left, int right) { int i, j; int pivot; if(left + CUTOFF <= right) { pivot = Median3(A, left, right); i = left + 1; j = right - 2; for(;;) { while(A[i] < pivot) i++; while(A[j] > pivot) j--; if(i < j) { Swap(&A[i], &A[j]); } else { break; } } Swap(&A[i], &A[right - 1]); QSort(A, left, i - 1); QSort(A, i + 1, right); } else { InsertionSort(A + left, right -left + 1); } }