#include <stdio.h>
#include <assert.h>
#define uint unsigned int
int binary_search(const int arr[], int len, int val) {
if (arr == NULL) {
return -1;
}
if (len < 1) {
return -1;
}
int left = 0;
int right = len - 1;
int ans = -1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == val) {
ans = mid;
break;
} else if (arr[mid] > val) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return ans;
}
#define TEST_NUM 22
int main() {
int i;
int arr[TEST_NUM] = {0, };
for(i=0; i < TEST_NUM; ++i){
arr[i] = i;
}
for (int i = 0; i < TEST_NUM; ++i) {
assert(binary_search(arr, sizeof(arr)/sizeof(int), i) == i);
}
assert(binary_search(arr, sizeof(arr)/sizeof(int), i) == -1);
return 0;
}