0

So, whenever i try to search for A[0] element(23 in this case). It don't return the position of the element. However, it works fine when i try to search for other elements then A[0]. Please tell what is wrong with the code and how can i fix it. Sample Output-- Enter item to search- 23 output- Element 23 could not be found in this array. Thanks in advance!

#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.";
    }
}
2
  • Why not use the standard library binary search algorithm, std::lower_bound? Ex. auto i = std::lower_bound(std::begin(A), std::end(A), item); if (i != std::end(A) && *i == item) index = i - std::begin(A); Commented Aug 27, 2017 at 16:16
  • Yes indeed sir. As a newbie in "Data Structures" i need to research on various libraries. And I also have to convert it into C. But thank you for the comment. Commented Aug 27, 2017 at 16:38

2 Answers 2

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

An index starts at 0 in an array. Hence, modify the IF condition to check for INDEX >= 0. If the input element is not found then INDEX will be returned as -1.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir! that was spot on. And of course a stupid mistake.
1

you have put if index!=0 condition but 23 is at index 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.