二分查找
#include <stdio.h>
int main(void) {
int arr[] = {-2, -1, 0, 1, 2, 3}; //数组
int l = 0;
int r = sizeof (arr) / sizeof(int) - 1; //计算数组的大小,然后 - 1就是最右侧的下标
int m, n;
scanf("%d", &n); //输入要查找的元素
while (l <= r) {
m = (l + r) / 2;
if (arr[m] == n) {
printf("找到了,是%d, 下标是%d\n", arr[m], m);
break;
}
else if (n > arr[m]) {
l = m + 1;
}
else {
r = m - 1;
}
}
if (l > r) {
printf("找不到\n");
}
return 0;
}
标签:二分,arr,int,查找,数组,sizeof
From: https://www.cnblogs.com/codels/p/17840426.html