2017-08-27 22 views
0

因此,每當我嘗試搜索A [0]元素(本例中爲23)時。它不返回元素的位置。但是,當我嘗試搜索其他元素,然後A [0]時,它工作正常。請說明代碼有什麼問題,我該如何解決這個問題。 輸出樣本 - 輸入要搜索的項目 - 23 輸出 - 在此陣列中找不到元素23。 在此先感謝!二進制搜索代碼無法找到數組的A [0]元素

#include <iostream> 
using namespace std; 
int main(){ 
    int A[]= {23, 34, 45, 67, 75, 89}; 
    int I= sizeof(A)/sizeof(A[0]); 
    int LAST= I-1, FIRST= 0, MID, ITEM, INDEX= 0; 
    MID= ((FIRST + LAST)/2); 
    cout<<"Enter item to search- "; 
    cin>>ITEM; 
    while(FIRST <= LAST){ 
     if(A[MID] == ITEM){ 
      INDEX= MID; 
      break; 
     } 
     else if(A[MID] < ITEM){ 
      FIRST= MID+1; 
     } 
     else{ 
      LAST= MID-1; 
     } 
     MID= ((FIRST + LAST)/2); 
    } 
    if(INDEX != 0){ 
     cout<<"\nElement "<<ITEM<<" found at position "<<(INDEX+1); 
    } 
    else{ 
     cout<<"\nElement "<<ITEM<<" could not be found in this array."; 
    } 
} 
+0

爲什麼不使用標準庫二進制搜索算法,'的std :: lower_bound'?防爆。 'auto i = std :: lower_bound(std :: begin(A),std :: end(A),item); if(i!= std :: end(A)&& * i == item)index = i - std :: begin(A);' –

+0

確實是先生。作爲「數據結構」的新手,我需要研究各種圖書館。而且我也必須將它轉換爲C.但是,感謝您的評論。 – TroubleShooter

回答

2
if(INDEX >= 0){ 
    cout<<"\nElement "<<ITEM<<" found at position ". 
      <<(INDEX+1); 
    } 

索引數組中的從0開始。因此,修改IF條件以檢查INDEX> = 0.如果未找到輸入元素,則INDEX將返回-1。

+0

謝謝先生!那是現貨。當然,這是一個愚蠢的錯誤。 – TroubleShooter

1

你已經把if index!=0條件,但23是在索引0