hi everyone,
I was practicing binary search with array and encountered a problem.
My code works but I can't help to make one part of it better.
Well look at my code to understand my question better.
int binary_search(int arry[], int size)
{
int first = 0;
int last = size;
int middle;
int key;
cout<<"What number would you like to search for in the arry : ";
cin>>key;
for(int i=0;i<size;i++)
{
middle = ((first)+(last)) / 2;
if(arry[middle]==key)
{
return middle;
break;
}
else if(arry[middle] > key)
last = middle-1;
else if (arry[middle] < key)
first = middle+1;
if(key > arry[last])
{
cout<<"\n\n\n"<<key<<" is not in this array. \n\n"<<endl;
exit(1);//IT IS THIS PART THAT I AM CONFUSED. I KNOW THERE IS SOME BETTER TO GO ABOUT THIS CASE THAN USING EXIT(1);
}
}
}