给定问题
以非递归方式实现二进制搜索算法。 将搜索数组保持为数字数组,在声明时初始化并保持全局。 程序应该要求搜索一个值,然后告诉它找到它的位置。 如果未找到该值,则程序应显示未找到。 *此外,程序应显示完成的比较总数以找到值(或意识到未找到该值)
我的解决方案
#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 ,行为定位值而进行的比较总数将被打印两次。
答案 0 :(得分:1)
这只是因为你两次调用二进制搜索功能。 一个在if部分,另一个在else,如果是part。
或者你可以按照以下方式做同样的事情
int temp = bi_search(n);
if (temp == -1)
printf("Value not found\n");
else
printf("Value found at position %d\n", temp);
答案 1 :(得分:1)
您正在调用bi_search
功能两次。进入if
语句后,再次进入printf
语句。您应该只调用一次,并缓存该值。
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) // Calling it here
printf("\nSORRY :( !! \nThe value was not found.");
else
printf("\nHurray :) !! \nThe value you entered found at %d position", bi_search(n)+1); // And here
printf("\nEnter:-\n\t1 to continue.\n\t2 to terminate.\n");
scanf("%d",&ch);
}while(ch==1);
printf("\nThank You\n");
return 0;
}
答案 2 :(得分:0)
您的主要例程如下:
int main()
{
int n = 0, ch = 0;
do
{
printf("\nEnter the value you want to search for--\n");
scanf("%d", &n);
int res = bi_search(n); // store the result
if (res == -1) // check if not find
printf("\nSORRY :( !! \nThe value was not found.");
else
printf("\nHurray :) !! \nThe value you entered found at %d position", res + 1); // print if find
printf("\nEnter:-\n\t1 to continue.\n\t2 to terminate.\n");
scanf("%d", &ch);
} while (ch == 1);
printf("\nThank You\n");
return 0;
}
1)int main()(使编译器平静)
2)int res = bi_search(n)(以避免第二次bi_search()调用)