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.";
}
}
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);