1 #include <stdio.h> 2 3 #define NotFound -1; 4 typedef int ElementType; 5 6 int BinarySearch( const ElementType A[], ElementType X, int N ) 7 { 8 int Low, Mid, High; 9 10 Low = 0; High = N-1; 11 while( Low <= High ) // 注意终止条件 12 { 13 Mid = (Low + High) / 2; 14 if( A[Mid] < X ) 15 Low = Mid + 1; 16 else if( A[Mid] > X ) 17 High = Mid - 1; 18 else 19 return Mid; 20 } 21 return NotFound; 22 } 23 24 int main() 25 { 26 int arr[10] = {1, 2, 3, 5, 6, 7, 9, 10, 12, 15}; 27 int sizeofA = sizeof(arr) / sizeof(arr[0]); 28 printf("BinarySearch returns %d ", BinarySearch(arr, 9, sizeofA)); 29 return 0; 30 }