1 #include<stdio.h> 2 #define N 10 3 4 void QuickSort(int a[],int left, int right); 5 int BinSearch(int a[], int low, int high, int key); 6 int main() 7 { 8 int a[N] = {2,8,4,9,7,6,5,3,1,0}; 9 int j = 0, i; 10 QuickSort(a, 0, sizeof(a)/sizeof(a[0])-1); 11 i = BinSearch(a, 0, N-1, 6); 12 printf("%d ", i); 13 for(j = 0; j < N; j++){ 14 printf("%d ",a[j]); 15 } 16 printf(" "); 17 return 0; 18 } 19 //折半查找 20 int BinSearch(int a[], int low, int high, int key){ 21 while(low <= high){ 22 int mid = (low + high) / 2; 23 if(a[mid] < key) 24 low = mid + 1; 25 else if(a[mid] > key) 26 high = mid - 1; 27 else 28 return mid; //查找成功 29 } 30 31 return -1; //查找失败 32 } 33 34 void QuickSort(int a[],int left, int right){ 35 int key = a[left]; 36 int i = left; 37 int j = right; 38 if(left >= right){ 39 return; 40 } 41 while(i < j){ 42 while(i<j && a[j] >= key){ 43 j--; 44 } 45 a[i] = a[j]; 46 while(i<j && a[i] <= key){ 47 i++; 48 } 49 a[j] = a[i]; 50 51 } 52 53 a[i] = key; 54 QuickSort(a, left, i-1); 55 QuickSort(a, i+1, right); 56 }