天天看點

二分查找(非遞歸)

設a[0:n-1]是一個已排好序的數組。請改寫二分搜尋算法,使得當搜尋元素x不在數組中時,傳回小于x的最大元素的位置I和大于x的最小元素位置j。當搜尋元素在數組中時,I和j相同,均為x在數組中的位置。

感覺這個題目挺簡單的,是以直接上代碼了!

#include <iostream>
using namespace std; 

bool BinarySearch(int a[],int n,int x,int &i,int &j);
//n表示數組長度 
int main() {
    int a[]={,,,,,};
    int n=sizeof(a);
    int x;
    int i=,j=;
    cout<<"請輸入要查找的數:"<<endl;
    cin>>x;
    if(BinarySearch(a,n,x,i,j)){
        cout<<"元素 "<<x<<" 在數組中的位置為 "<<i<<endl; 
    }
    else{
        cout<<"數組中小于 "<<x<<"的最大元素為 "<<a[i]<<endl;
        cout<<"數組中大于 "<<x<<"的最小元素為 "<<a[j]<<endl;
    }
    return ;
}

bool BinarySearch(int a[],int n,int x,int &i,int &j) {
    int left=;
    int right=n-;
    while(left<=right){
        int mid=(left+right)/;
        if(x==a[mid]){
            i=j=mid;
            return true;
        }
        if(x>a[mid]){
            left=mid+;
        }
        else{
            right=mid-;
        }
    }
    i=right;
    j=left;
    return false;
} 
           

這段代碼在vs裡能夠實作,但在Dev-c++裡卻運作不成功,糾結了很久也不知道原因,還望有人賜教。

繼續閱讀