QSort
1 #include<stdio.h> 2 void swap(int *p, int *q); 3 int median3(int *array, int left, int right); 4 void qsort(int *array, int left, int right); 5 6 void main() 7 { 8 int a[] = {2,3,1}; 9 //int array[] = {29, 7, 14, 20, 27, 11, 25, 0, 28, 26}; 10 int array[] = {23, 5, 6, 11, 29, 21, 8, 27, 8, 15}; 11 //int array[] = {0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff}; 12 int i; 13 //printf("%d\n", a[median3(a, 0, 2)]); 14 //swap(&a[0], &a[1]); 15 //printf("%d %d\n", a[0],a[1]); 16 qsort(array, 0, 9); 17 for(i=0; i<10; i++) 18 printf("%d ", array[i]); 19 } 20 21 22 void qsort(int *array, int left, int right) 23 { 24 int low = left+1; 25 int high = right; 26 int pivot; 27 28 if(right-left <=0) 29 return; 30 31 swap(&array[left], &array[median3(array, left, right)]); 32 pivot = array[left]; 33 //printf("\n*%d*\n", pivot); 34 while(1) 35 { 36 while((low < high) && (array[low] <= pivot)) 37 { 38 printf("$: %d\n", array[low] ); 39 low++; 40 } 41 while(array[high] > pivot) 42 high--; 43 if(low<high) 44 { 45 swap(&array[low], &array[high]); 46 low++; 47 high--; 48 } 49 else 50 break; 51 } 52 swap(&array[high], &array[left]); 53 qsort(array, left, high-1); 54 qsort(array, high+1, right); 55 } 56 57 int median3(int *array, int left, int right) 58 { 59 int mid = (left + right)/2; 60 61 if(array[left] < array[mid]) 62 if(array[mid] < array[right]) 63 return mid; 64 else 65 return array[left]>array[right] ? left : right; 66 else 67 if(array[mid] > array[right]) 68 return mid; 69 else 70 return array[left]<array[right] ? left : right; 71 } 72 73 void swap(int *p, int *q) 74 { 75 int temp; 76 temp = *p; 77 *p = *q; 78 *q = temp; 79 }