【发布时间】:2015-02-25 18:00:22
【问题描述】:
给定问题
以非递归方式实现二分查找算法。 将搜索数组保留为数值数组,在声明时初始化并保持全局。 程序应该要求搜索一个值,然后告诉它找到的位置。 如果未找到该值,则程序应显示未找到。 * 此外,程序应显示为定位值而进行的比较总数(或意识到未找到该值)
我的解决方案
#include<stdio.h>
int arr[]={1,3,4,6,8,9,10,15,17,21};
int bi_search(int n)
{
int start=0,end=9,mid=0,count=0;
while(start<=end)
{
count++;
mid=(start+end)/2;
if(n==arr[mid])
{
printf("\nThe total number of comparisons done to locate the value--%d\n",count);
return mid;
}
else if(n<arr[mid])
end=mid-1;
else
start=mid+1;
}
printf("\nThe total number of comparisons done to realize that the value was not found--%d\n",count);
return-1;
}
main()
{
int n=0,ch=0;
do
{
printf("\nEnter the value you want to search for--\n");
scanf("%d",&n);
if(bi_search(n)==-1)
printf("\nSORRY :( !! \nThe value was not found.");
else
printf("\nHurray :) !! \nThe value you entered found at %d position", bi_search(n)+1);
printf("\nEnter:-\n\t1 to continue.\n\t2 to terminate.\n");
scanf("%d",&ch);
}while(ch==1);
printf("\nThank You\n");
return 0;
}
当我运行此代码时,在函数 bi_search(int n) 中,只要 arr[mid] 等于 n,行 >为定位值而进行的比较总数--被打印两次。
【问题讨论】:
标签: c arrays runtime-error binary-search