折半查找.txt
来自「数据结构课堂实验 集中了数据结构,线性表,连表,栈,队列,二叉树,图,排序算法」· 文本 代码 · 共 32 行
TXT
32 行
#include <stdio.h>
int BinarySearch(int a[], int n, int key)
{ int low,high,mid;
low=1; high=n;
while(low<=high)
{ mid=(low+high)/2;
if(key==a[mid]) return mid;
else if(key<a[mid]) high=mid-1;
else low=mid+1;
}
return 0;
}
void CreatSearchTable(int a[],int n) /*创建查找表,且为递增有序的*/
{ int i;
printf("Input %d numbers:", n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
}
main()
{int a[30], key;
int n,loc;
n=11;
CreatSearchTable(a,n);
printf("Input a number to search:");
scanf("%d",&key);
loc=BinarySearch(a,n,key);
if(loc) printf("%d is found!! Position is %d!!\n",key,loc);
else printf("%d is not found!!!\n",key);
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?