快速排序实例
快速排序函数:
/* quick_sort.h */ #ifndef _QUICK_SORT_H #define _QUICK_SORT_H #define CUTOFF (3) void quick_sort(int array[], int n); //快速排序的驱动例程 int median3(int array[], int left, int right); //实现三数中值分割 void qsort(int array[], int left, int right); //快速排序主例程 #endif
/* quick_sort.c */ #include "quick_sort.h" #include "common.h" #include "insertion_sort.h" void quick_sort(int array[], int n) { qsort(array, 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]; } void qsort(int array[], int left, int right) { int i, j; int pivot; if(left + CUTOFF <= right) { pivot = median3(array, left, right); i = left; j = right - 1; for(;;) { while(array[++i] < pivot){} while(array[--j] > pivot){} if(i < j) swap(&array[i], &array[j]); else break; } swap(&array[i], &array[right - 1]); qsort(array, left, i - 1); qsort(array, i + 1, right); } else insertion_sort(array + left, right - left + 1); }
注:上面程序中,common.h参考:http://www.cnblogs.com/nufangrensheng/p/3665397.html;insertion_sort.h参考:http://www.cnblogs.com/nufangrensheng/p/3657887.html
测试程序:
/* quick_sort_test.c */ #include "quick_sort.h" #include "common.h" #include <stdio.h> int main(void) { int array[] = {8, 1, 4, 9, 0, 3, 5, 2, 7, 6}; printf("Before sorted : "); print_array(array, 10); printf("After sorted : "); quick_sort(array, 10); print_array(array, 10); return 0; }
Makefile:
/* Makefile */ target := test objs := quick_sort_test.o quick_sort.o common.o insertion_sort.o $(target):$(objs) gcc -o $@ $^ %.o:%.c gcc -c -o $@ $< clean: rm *.o test
测试结果: