簡體   English   中英

為什么這個 C++ 程序沒有顯示任何 output?

[英]Why is this C++ program not showing any output?

我正在嘗試為二進制搜索編寫代碼,但它沒有顯示任何 output。 請告訴我我的錯誤。

#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;
}

你計算mid的方式不對,應該是這樣的:

int mid = (first + last) / 2;

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

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

或使用>>運算符:

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

您的二進制搜索代碼沒有產生任何 output 的原因是因為存在一些邏輯錯誤,例如:

  • 您正在使用不正確的方法來查找中間值,找到中間值的適當方法是:

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

以下是更新后的二分搜索代碼,並附有一些有用的注釋:

#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; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM