Description
编写Search_Bin函数,实现在一个递增有序数组ST中采用折半查找法确定元素位置的算法.
输入格式
第一行:元素个数n 第二行:依次输入n个元素的值(有序) 第三行:输入要查找的关键字key的值
输出格式
输出分两种情形: 1.如果key值存在,则输出其在表中的位置x(表位置从0开始),格式为The element position is x. 2.如果key值不存在输出:"The element is not exist."
输入样例
6 1 3 5 7 9 10 5
输出样例
The element position is 2.
#include<stdio.h>
#include<string.h>
int search_bin(int *num, int n, int key)
{
int left = 0, right = n-1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (num[mid] == key)
return mid;
else if (num[mid] < key)
left = mid + 1;
else if (num[mid] > key)
right = mid - 1;
}
return -1;
}
int main()
{
int num[1000], n, i, ans = -1, key;
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &num[i]);
scanf("%d", &key);
ans = search_bin(num, n, key);
if (ans== -1)
printf("The element is not exist.\n");
else
printf("The element position is %d.\n", ans);
return 0;
}
二分查找那部分也可以用递归来做,稍微在这个代码的基础上改一改就可以了,但是我懒就不码出来了,求知的可以自己码出来吧。