写代码---每日一题(二分查找)
大家好,我是KookNut39,在这里分享我所学的一些知识,希望可以帮助你进步,更希望能成为你生活中的朋友。大家如果遇到了任何的问题,都可以找我倾诉,我有空的时候,一定及时回复大家,愿大家心中有梦,眼中有光,一往无前!
b) 编写main函数,调用BinSearch函数,实现在10个数据元素的有序表{2,4,7,9,10,14,18,26,32,40}中采用折半查找方法,查找关键字7和25。
#include<stdio.h>
typedef int KeyType, ElemType;
typedef struct _SQ_TYPE_
{
KeyType key;
ElemType data;
}SqType;
int BinSearch(SqType R[], int n, KeyType k)
{
int low = 0;
int high = n - 1;
int mid = 0;
int count = 0;
while (low <= high)
{
count++;
mid = (low + high) / 2;
printf("在[%d...%d]查找,与R[%d].data=%d比较,", low, high, mid, R[mid].data);
if (R[mid].data == k)
{
printf("相等\n");
printf("共比较%d次\n", count);
printf("查找%d成功,逻辑序号是%d\n", k, R[mid + 1].key);
return 0;
}
else
{
printf("不相等\n");
if (R[mid].data > k)
{
high = mid - 1;
}
else
{
low = mid + 1;
}
continue;
}
}
printf("共比较%d次\n", count);
printf("查找%d失败\n",k);
return 0;
}
void main()
{
int n = 10;
int k = 0;
SqType R[] = { {0,2},{1,4},{2,7},{3,9},{4,10},{5,14},{6,18},{7,26},{8,32},{9,40} };
printf("查找表:");
for (int i = 0; i < 10; i++)
{
printf("%3d", R[i].data);
}
printf("\n请输入需要查找的数字:");
scanf("%d", &k);
printf("\n查找关键字:%d\n",k);
BinSearch(R, n, k);
}