Question
Find a target value in a Sorted array of N integers and print it's index in Logarithmic time.
Need of Binary Search
So, why do we need Binary search, Let us perform a Linear Search and go through the integer array one element at a time, it would result in O(N)
Time complexity for the worst case ( N is the number of integers present in the array ).
Binary Search helps us in reducing this time to O(log2n)
.
How Binary Search works?
Binary Search is a Divide and Conquer algorithm, that divides the array into subarrays that are exactly half in size and these subarrays divide into further subarrays until we find our element. We need to define 3 variables i.e. Start, Mid and End.
Binary Search finally boils down to 3 steps :
if(target == nums[mid]) return mid;
if(target < nums[mid]) end = mid - 1;
if(target > nums[mid]) start = mid + 1;
Source Code (Iterative) :
// Iterative Binary Search
public static int binarySearch(int[] nums, int target)
{
int Start= 0, End = nums.length - 1;
// loop till the search space is exhausted
while (Start <= End)
{
// find the mid-value in the search space
int mid = End - (End - Start) / 2;
// target is found
if (target == nums[mid]) {
return mid;
}
// discard all elements in the right search space,
// including the middle element
else if (target < nums[mid]) {
End = mid - 1;
}
// discard all elements in the left search space,
// including the middle element
else {
Start = mid + 1;
}
}
// `target` doesn't exist in the array
return -1;
}
Source Code (Recursive) :
// Recursive Binary Search
public static int binarySearch(int[] nums, int Start, int End, int target)
{
// Base condition (we reached the end of the array)
if (Start > End) {
return -1;
}
// mid value (to avoid OverFlow, we use mid like this)
int mid = left + (right - left) / 2;
// Base condition (We found our target)
if (target == nums[mid]) {
return mid;
}
// if the target is smaller than mid then it must be present before mid
// So we discard the values from mid to end
else if (target < nums[mid]) {
return binarySearch(nums, Start, mid - 1, target);
}
// if the target is bigger that mid then it must be present after mid
// So we discard the values from Start to Mid
else {
return binarySearch(nums, mid + 1, End, target);
}