Write the code for follow binary comparison treeSolution1 in
Write the code for follow binary comparison tree
Solution
1. int BinarySearch1(int array, int low, int high, int key)
{
int mid = (low + high) / 2;
if(key == array[mid])
return mid;
else if(key < array[mid])
return BinarySearch(array, low, mid); //Here actually, an element is being compared excessively which will increase the number of comparisons.
else
return BinarySearch(array, mid+1, high);
}
2. int BinarySearch2(int array, int low, int high, int key)
{
int mid = (low + high) / 2;
if(key == array[mid])
return mid;
else if(key < array[mid])
return BinarySearch(array, low, mid-1); //Here the efficiency is improved by excluding the element which is already compared in the if block.
else
return BinarySearch(array, mid+1, high);
}
