- 写代码可以整形有序数组中查找想要的数字,找到了返回下标,找不到返回-1(折半查找)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int main(){
int arr[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
int left = 0;
int right = sizeof(arr)/sizeof(arr[0])-1;
int mid = 0;
int i = 0;
printf(“请输入一个整数:\n”);
scanf("%d", &i);
while (left <= right){
mid = (left + right) / 2;
if (i < arr[mid]){
left = mid + 1;
}
else if (i>arr[mid]){
right = mid - 1;
}
else {
break;
}
}if (left <= right){
printf("%d\n", mid);
}
else{
printf("%d\n", -1);
}
system(“pause”);
return 0;
}
写代码可以整形有序数组中查找想要的数字,找到了返回下标,找不到返回-1(折半查找)
最新推荐文章于 2020-01-25 14:53:09 发布