额,都不知道类别应该选择成神马才合适。
#include<cstdio>
int binary(int *arr, int size, int searchValue);
int main(){
// int arr[] = { 2 5 8 9 12 56 87 99 }; e, nothing to say...
int arr[] = { 2, 5, 8, 9, 12, 56, 87, 99 };
int size = sizeof(arr) / sizeof(int);
int i;
int index;
for(i = 0; i < size; ++i){
index = binary(arr, size, arr[i]);
printf("the return index of binary search for arr[%d] is %d.\n", i, index);
}
index = binary(arr, size, 106);
printf("the return index of binary search for 106 is %d.\n", index);
index = binary(arr, size, 1);
printf("the return index of binary search for 1 is %d.\n", index);
index = binary(arr, size, 50);
printf("the return index of binary search for 50 is %d.\n", index);
return 0;
}
int binary(int *arr, int size, int searchValue){
int first = 0;
int last = size - 1;
int mid;
while(first <= last){ // can not write as while(first < last)
mid = (first + last) / 2;
if(arr[mid] == searchValue){
return mid;
} else if (arr[mid] > searchValue) {
last = mid - 1;
} else {
first = mid + 1;
}
}
return -1;
}