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

}

this is binary search algorithm...hope u understand this...

int BinarySearch(int arr[], int value, int low, int high) 
{
       if (high < low)
           return -1; // not found
       int mid = (low + high) / 2;
       if (arr[mid] > value)
           return BinarySearch(arr, value, low, mid-1);
       else if (arr[mid] < value)
           return BinarySearch(arr, value, mid+1, high);
       else
           return mid; // found
}

You don't need to use an emergency bailout like that.
If it's member of a class then you could have it set one variable that indicates an error occurred, or didn't find anything.

class SearchTools : public MaybeSomeOtherLibTools
{
    private:
        bool error;
        bool success;

    public:
        int binary(...);

        bool isError(void);
        bool isSuccess(void);
};

Have the constructor set the default values.

or....

int binary_search(int arry[], int size)
{
	int first = 0;
	int last = size - 1;
	int middle = 0;
	int key = 0;
	cout<<"What number would you like to search for in the arry : ";
	cin>>key;
	for(;first<=last;)
	{
			middle = ((first)+(last)) / 2;
			
			if(arry[middle] > key)
				last = middle-1;
			else if (arry[middle] < key)
				first = middle+1;
			else 
			    return middle;
	}
	std::cout<<"??? Not found\n";
	return -1;
}

you can just break;

or you can do this

creat bool notfound = false; out side the for loop
	 if(key > arry[last])
	 {
                 notfound = true;
	}

      and after the for terminate you can check and see if notfound is equal to true
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.