1 /* quicksort */
2 #include<stdio.h>
3
4 #define Cutoff (3)
5
6 InsertionSort(int A[], int n)
7 {
8 int tmp, i, j;
9
10 for(i = 1; i < n; i++){
11 tmp = A[i];
12 for(j = i; j > 0 && A[j - 1] > tmp; j--)
13 A[j] = A[j - 1];
14 A[j] = tmp;
15 }
16 }
17
18 void Swap(int *x, int *y)
19 {
20 int tmp;
21 tmp = *x;
22 *x = *y;
23 *y = tmp;
24 }
25
26 int Median3(int A[], int Left, int Right)
27 {
28 int Center = (Left + Right) / 2;
29
30 if(A[Left] > A[Center])
31 Swap(&A[Left], &A[Center]);
32 if(A[Left] > A[Right])
33 Swap(&A[Left], &A[Right]);
34 if(A[Center] > A[Right])
35 Swap(&A[Center], &A[Right]);
36
37 /* Invariant: A[Left] <= A[Center] <= A[Rignt] */
38
39 Swap(&A[Center], &A[Right - 1]); /* Hide pivot */
40 return A[Right - 1]; /* Return pivot */
41 }
42
43 void Qsort(int A[], int Left, int Right)
44 {
45 int i, j;
46 int Pivot;
47
48 if(Left + Cutoff <= Right){
49 Pivot = Median3(A, Left, Right);
50 i = Left, j = Right - 1;
51 for( ; ; ){
52 while(A[++i] < Pivot){
53 }
54 while(A[--j] > Pivot){
55 }
56 if(i < j)
57 Swap(&A[i], &A[j]);
58 else
59 break;
60 }
61 Swap(&A[i], &A[Right - 1]); /* Restore pivot */
62
63 Qsort(A, Left, i - 1);
64 Qsort(A, i + 1, Right);
65 }
66 else /* Do an insertion sort on the subarray */
67 InsertionSort(A + Left, Right - Left + 1);
68 }
69
70 void Quicksort(int A[], int N)
71 {
72 Qsort(A, 0, N - 1);
73 }
74
75 int main(void)
76 {
77 int i, num;
78 int array[] = {8,1,4,9,0,3,5,2,7,6};
79 num = sizeof(array) / sizeof(int);
80 Quicksort(array , num);
81 for(i = 0; i < num; i++){
82 printf("array[%d] = %d\n", i, array[i]);
83 }
84
85 return 0;
86 }
http://www.zentut.com/c-tutorial/c-quicksort-algorithm/