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";
cin>>input;
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";
cin>>quit;
if ( quit=='n' || quit =='N')
break;
}
system("PAUSE");
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;
else
right = mid - 1;
}
return 0;
// code is IP of 09030032 [at] lums
}