'Binary Search in C plus plus
the code when executes creates an infinite loop.
What is wrong with this code :-(
using namespace std;
int main(){
int arr[10]={1,20,30,75,90,189,253,302,304,455}, start=0, end=9, item, mid, i;
cin>>item;
mid=(start+end)/2;
while(arr[mid]!=item){
mid=(start+end)/2;
if(item>mid){
start=mid+1;
}
else if(item<mid){
end=mid-1;
}
}
cout<<"Found at location : "<<mid<<endl;
return 0;
}
Solution 1:[1]
Answering your actual question: "What is wrong with this code?", see comments below:
using namespace std;
int main(){
int arr[10] = {1,20,30,75,90,189,253,302,304,455}, start=0, end=9, item, mid, i;
cin >> item;
mid = (start+end) / 2;
// You function loops indefinitely... The first place to look is here, at
// the test for your loop.
// One thing is quite plain here : You will loop indefinitely if the item you
// search for is not in the list.
//
// You should also stop looping when your search interval has reduced to
// nothingness, as this indicates the item is not found...
//
while (arr[mid] != item) { // <-- BUG
// try this instead:
while (start <= end) { // loop while interval size is >= 1 ('end' is inclusive)
const int mid = (start + end) / 2;
// Check for search success here:
if (arr[mid] == item)
{
cout << "Found at location : " << mid << endl;
return 1; // we're done! exit loop
}
if (item > mid) { // <-- BUG!!!
// should be
if (arr[mid] < item)
start = mid + 1;
else
end = mid - 1;
}
cout << "Not found." << endl;
return 0;
}
Solution 2:[2]
using namespace std;
int main(){
int arr[10]={1,20,30,75,90,189,253,302,304,455}, start=0, end=9,
item, mid, i;
cin>>item;
bool found = true;
mid=(start+end)/2;
while(arr[mid]!=item ){
mid=(start+end)/2;
if(item > **arr[mid]**){
start=mid+1;
}
else if(item< **arr[mid]**){
end=mid-1;
}
if ( start > end ){ // termination condition
found = false; break;
}
}
if ( found ) std::cout<<"Item found at: "<<mid<<std::endl;
else std::cout<<"Item not found."<<std::endl;
}
See the changes between ** in the if checks inside the loop. It works now.
EDIT: Added a termination condition if the element is NOT found in the array. Your original code was looping infinitely because your conditions were wrong. The corrections in ** fixed the condition when the searched for element was actually inside the array. And now the termination condition takes care of the last case of infinite loop as well.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
