The following binary search code runs perfect .

I feed values that exist in the array and it tells me at what location they are.

But if i enter a value non-existent in the array it goes bad.

It says number not in array and after that...

Any other value i enter after this wrong value is not in the array even thought initially it was in this array....

#include <iostream>
#include <cstdlib>

using namespace std;

const int arrSize = 100;  
bool isPresent(int theArr[arrSize], int n);
int main()
    int myArr[arrSize];
    int input;
    char quit;         // input inquiry for quit or continue
    bool j;            // j is assigned the return value
    for (int i=0; i<=arrSize; i++)
        myArr[i]=rand();      //creating array with random numbers
    //sorting random numbers
    for (int j=0; j<=arrSize; j++){
        for(int k=0; k<j ; k++){        
            if (myArr[j] < myArr[k]){
               myArr[k] = myArr[j] + myArr[k];                       
               myArr[j] = myArr[k] - myArr[j];
               myArr[k] = myArr[k] - myArr[j];
    //display array
    for (int i=0; i<=arrSize; i++)
        { cout<<myArr[i]<<" ";
          if ( i%6==0 ) cout<<endl; }
    while (1)
    cout<<"\n Enter number to check in the array: \n";
    j= isPresent( myArr, input );
    if (j==1)
    cout << "Success. The item was found."<< endl;
    if ( j==0)
    cout << "The item was not in the array\n";

    cout<<" Do you want to check for another number?\n";
    if ( quit=='n' || quit =='N')

    return 0;


// function code 

bool isPresent(int theArr[arrSize], int n)
     int left=0, right, mid=0;
     right = arrSize - 1;

     while (left <= right)
     mid = ((left + right) / 2);
     if (n == theArr[mid])
     { cout<<"Found @ location:"<<mid<<endl;
           return 1;      }

       else if (n > theArr[mid])
     left = mid + 1;
     right = mid - 1;

return 0;
 // code is IP of 09030032 [at] lums   

Edited by Der_sed: n/a

9 Years
Discussion Span
Last Post by vmanes

first this is wrong :

for (int i=0; i<=arrSize; i++)  //it should be   i < arrSize
        myArr[i]=rand();      //creating array with random numbers

The same goes for sorting and displaying numbers.


it didn't work when first input was a negative number then the next
input was the last number in the solution grid.


go back to firstPerson's comment - what you see as the "last" element in your array is actually index 100 (item #101 !!). Your fill, sort and display go one step to far, but your search is correct, so it cannot possibly find that ghost element.

Remember, the canonical loop for walking an array is:

for( i = 0; i < arr_size; i++ )

Use a strictly less than test and you'll stay safe.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.