Search code examples
c++binary-search

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

  • 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;
    }