4
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by Jacky1
0

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
}
0

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.

0

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

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
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.