二分法查找一个有序数组中是否有某个数
大家看了可以自己写一下
(
要用知识点
数组
while循环
scanf 函数
printf函数
)
//用二分法查找
#include<stdio.h>
int main()
{char arr[] = { 1,2,3,4,5,6,7,8,9,10 };int sz = sizeof(arr) / sizeof(arr[1]);//输入查找的数int k = 0;char a = '0';do{int left = 0;int right = sz - 1;printf("请输入一个数\n");scanf_s("%d", &k);while (left <= right){int mid = (left + right) / 2;if (arr[mid] == k){printf("找到了,下标是%d\n", mid); break;}else if (mid < k) left = mid + 1;else right = mid - 1;}if (left > right) printf("找不到");int i = getchar();printf("请问是否继续【yes-y no -n】\n");scanf_s("%c", &a);} while (a == 'y' || a == 'Y');return 0;
}