C语言的快速排序
2分快速排序
C代码:
1 typedef unsigned char BYTE; 2 3 void swap(BYTE *a, BYTE *b) 4 { 5 if(a != b) { 6 *a = *a ^ *b; 7 *b = *b ^ *a; 8 *a = *a ^ *b; 9 } 10 } 11 12 /*** 13 *2路划分快速排序 14 * 15 **/ 16 int partition(BYTE *array, int left, int right) 17 { 18 int i = left - 1, j = right; 19 BYTE v = array[right]; 20 while(1) { 21 while(array[++i] < v); 22 while(array[--j] > v) 23 if(j == 1) 24 break; 25 if(i >= j) 26 break; 27 printf("i = %d, j = %d\n", i, j); 28 swap(&array[i], &array[j]); 29 } 30 swap(&array[i], &array[right]); 31 printf("i = %d, right = %d\n", i, right); 32 33 return i; 34 } 35 36 void quicksort(BYTE *array, int left, int right) 37 { 38 if(left < right) { 39 int i = partition(array, left, right); 40 quicksort(array, left, i - 1); 41 quicksort(array, i + 1, right); 42 } 43 }