【问题标题】:Why is this C++ program not showing any output?为什么这个 C++ 程序没有显示任何输出?
【发布时间】:2021-04-04 10:07:13
【问题描述】:

我正在尝试为二进制搜索编写代码,但它没有显示任何输出。请告诉我我的错误。

#include <iostream>
using namespace std;

int main(){
    int a[]= {1, 3, 5 , 7,  32};
    int n;
    cin>>n;
    int last=(sizeof(a)/sizeof(a[0]))-1;
    int first=0;
    while(first<=last){
        int mid=(last-1)/2;

        if(a[mid]==n){
            cout<<"No. Found"<< endl;
        }
        if(n>a[mid])
        {
            first=mid+1;
        }
        else
        {
            last=mid-1;
        }
    }
    cout<<"Not Found"<<endl;
    return 0;
}

【问题讨论】:

标签: c++


【解决方案1】:

你计算mid的方式不对,应该是这样的:

int mid = (first + last) / 2;

最好的方法是避免溢出(first + last 可以溢出):

int mid = first + (last - first) / 2;

或使用&gt;&gt; 运算符:

int mid = (first + last) >> 1;

【讨论】:

【解决方案2】:

您的 二分搜索 代码没有产生任何输出的原因是存在一些逻辑错误,例如:

  • 您使用了不正确的方法来找到中间值,找到中间值的适当方法是:

    mid = (f1 + f2) / 2** (where f1 = first, f2 = last)

以下是更新后的二分搜索代码,其中包含一些有用的 cmets:

#include <bits/stdc++.h> 
using namespace std; 
      
// A Iterative Binary Search Function.
    
int BinarySearch(int arr[], int low, int r, int x) 
{ 
    while (low <= r)
    { 
        int mid = low + (r - low) / 2; 
      
        // To check whether int x is at mid or not. 
            
        if (arr[mid] == x) 
        {
            return mid;
        } 
      
        // If x is greater than mid value, ignore the  left half 
        if (arr[mid] < x)
        { 
            low = mid + 1;
        } 
      
        // If x is smaller than mid-value, ignore the  right half 
        else
        {
            r = mid - 1;
        } 
    } 
      
    // if your desired element is not there 
    return -1; 
} 
      
int main(void) 
{ 
    int arr[] = {1, 3, 5, 7, 32}; 
    int x;
    cin >> x; 
    int n = sizeof(arr) / sizeof(arr[0]); 
    int result = binarySearch(arr, 0, n - 1, x); 
    if(result == -1)
    { 
        cout << "Element is not present in array"
        cout << "Element is present at index " << result << endl;
    }
    return 0; 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    相关资源
    最近更新 更多