二元搜索的逻辑

时间:2012-12-17 00:56:22

标签: c++ c binary-search

我在数据结构书中读到了二进制搜索的伪代码,然后我开始编写代码。我写的代码是:

#include <iostream.h>
#include <conio.h>
template <class T>

int BSearch(T x[], const int n, T item)
    {
    int loc, first = 0, found = 0, last = n-1;
        while(first <= last && !found)
        {
            loc = (first + last)/2;
            if(item < x[loc])
                last = loc - 1;
            else if(item > x[loc])
                first = loc + 1;
            else
                found = 1;
         }
      return found;
   }

int main()
    {
    const int n =5;
      int x[n],item;
      cout << "Pls enter " <<n<<" number(s): ";

      for(int i = 0; i < n;i++)
        cin >> x[i];
      cout << "Pls enter the item to Search: ";
        cin >> item;
      if(BSearch(x,n,item))
        cout << "\n\t Item Exist";
      else
        cout << "\n\t Item NOT Exist";

      getch();
      return 0;
   }

没有任何错误,但存在逻辑错误。它只是从BSearch函数返回0值,我只是得到这个消息“Item NOT Exist”。我的虫子在哪儿?我没找到。 感谢

3 个答案:

答案 0 :(得分:8)

二进制搜索仅适用于有序列表。但是你没有订购从std::cin获得的列表,因此你的二进制搜索会得到错误的结果。

要解决此问题,您必须将输入限制为预先排序的列表,或者您必须在进行二进制搜索之前先对列表进行排序。

答案 1 :(得分:4)

我尝试了你的代码,似乎工作正常。您必须记住,您输入的数字必须从小到大排序。

答案 2 :(得分:0)

二进制搜索涉及通过将范围除以其原始大小的一半来将搜索范围缩小到一半。二进制搜索按排序数组运行。它将此范围中间的元素与要搜索的值进行比较,如果该值小于中间值,则在从第一个元素到中间的范围内查找该值,否则新的搜索范围变为中间值最后一个元素此过程继续,直到找到所需元素或下限变得大于上限。二进制搜索的效率在平均和最差情况下是O(log2n)并且在最佳情况下是O(1)。执行二进制搜索的“C”程序如下:

/* Binary Search */
#include <stdio.h>

#define MAX 10

int main(){
int arr[MAX],i,n,val;
int lb,ub,mid;
printf(“nEnter total numbers?”);
scanf(“%d”,&n);
for(i=0;i<n;i++){
printf(“nEnter number?”);
scanf(“%d”,&arr[i]);
}
printf(“nEnter the value to search?”);
scanf(“%d”,&val);
lb=0;ub=n-1;
while(lb<=ub){
mid=(lb+ub)/2;
if(val<arr[mid])
ub = mid-1;
else if(val>arr[mid])
lb = mid+1;
else {
printf(“nNumber found…!”);
return;
}
}
printf(“nNumber not found…!”);
}
相关问题