记录一下
```C
#include<stdio.h>
int main() {
int a[100], key, index = -1, high, low, mid, i, m;
scanf("%d", &m);
for (i = 0; i < m; i++) {
scanf("%d", &a[i]);
}
scanf("%d", &key);
low = 0; high = key-1;
while (low <= high) { //目的是防止数组中没有查找的元素,如果没有需要的元素最终low会大于high
mid = (low + high) / 2;
if (a[mid] == key) {
index = mid; break;
}
else if (a[mid] <= key) {
low = mid + 1; //因为mid已经比较过所以+1
}
else if (a[mid] > key) {
high = mid - 1; //同上
}
else {
index = -1; break;
}
}
if (index == -1) {
printf("NULL");
}
else
printf("%d", index);
return 0;
}
参考
懒猫老师-C语言-二分查找(折半查找)_哔哩哔哩_bilibili
C语言二分查找法 - 尼古拉斯宝莉 - 博客园 (cnblogs.com)