题目:写代码可以在整型有序数组中查找想要的数字,
找到了返回下标,找不到返回-1.(折半查找)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(){
int arr[] = { 1,2,3,4,5,6,7,8,9 };
int to_find;
printf("请输入需要查找的数字(1-9):\n");
scanf("%d",&to_find);
int left = 0;
int right = sizeof(arr) / sizeof(arr[0]) - 1;
while (left<=right)
{
int mid = (left + right) / 2;
if (to_find < arr[mid]) {
right = mid - 1;
}//要找的数字小于中间数,右临界改为mid-1;
else if (to_find > arr[mid]) {
left = mid + 1;
}
else {
break;
}
}
if (left<=right) {
printf("找到了!\n");
}
else {
printf("没找到.\n");
}
system("pause");
return 0;
}