折半查找的方法
#include <stdio.h>#include <stdlib.h>
int main() {
int arr[10] = { 0 };
printf("请输入数组中的数,升序排列\n");
for (int i = 0; i < 10; i) {
scanf("%d", &arr[i]);
}
printf("请输入想要查找的数\n");
int num = 0;
scanf("%d", &num);
int left = 0;
int right = sizeof(arr) / sizeof(arr[0]) - 1;
while (1) {
int mid = (left right) / 2;
if (num > arr[mid]) {
left = mid 1;
}
if (num < arr[mid]) {
right = mid - 1;
}
if (num == arr[mid]) {
printf("找到了,下标是%d\n",mid);
break;
}
if (left>right) {
printf("没找到\n");
break;
}
}
system("pause");
return 0;
}
评论