本章講解的是快速排序算法,快速排序有不少變種,不過基本原理是同樣的。算法
int Partition(int *a, int low, int high) { int key = a[low]; while (low < high) { while (low < high && a[high] >= key) { high--; } a[low] = a[high]; while (low < high && a[low] <= key) { low++; } a[high] = a[low]; } a[low] = key; return low; } void QuickSort(int *a, int low, int high) { if (low < high) { int mid = Partition(a, low, high); QuickSort(a, low, mid-1); QuickSort(a, mid+1, high); } } int main(int argc, const char * argv[]) { int a[] = {3, 5, 1, 2, 5, 4}; int n = sizeof(a) / sizeof(*a); int low = 0; int high = n - 1; QuickSort(a, low, high); int i = 0; for (; i < n; i++) { printf("%d ", a[i]); } return 0; }
輸出:1 2 3 4 5 5 ide