1 #include <stdlib.h> 2 #include <stdio.h> 3 #include <string.h> 4 5 #define ARRAY_SIZE 10 6 7 int binarySearch(int *arr, int size, int target) 8 { 9 int low = 0; 10 int high = size - 1; 11 while (low < high) 12 { 13 int mid = low + (high - low) / 2; 14 //当low+high超过整数范围会发生溢出,变为负数 15 //int mid = (low + high) / 2; 16 if (arr[mid] < target) 17 { 18 low = mid + 1; 19 } 20 else if (arr[mid] > target) 21 { 22 high = mid - 1; 23 } 24 else 25 { 26 return mid; 27 } 28 } 29 return -1; 30 } 31 int main(int argc, char **argv) 32 { 33 int array_unsort[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 34 int pos = binarySearch(array_unsort, ARRAY_SIZE, 6); 35 printf("The target is in pos = %d\n", pos); 36 getchar(); 37 return 0; 38 39 }
来源:https://www.cnblogs.com/VincentLEcho/p/4206083.html