Binary Search Algorithm
Binary Search Algorithm
Binary search is a divide and conquer algorithm. Like all divide and conquer algorithms, Binary
Search first divides a large array into smaller sub-arrays and then operate the sub-arrays. But
instead of operating on both sub-arrays, it discards one sub-array and continue on the second
sub-array. This decision of discarding one sub-array is made in just one comparison.
So Binary Search basically reduces the search space to half at each step. By search space we mean
sub-array of given array where the target value is located (if present in the array). Initially, the
search space is the entire array and binary search redefine the search space at every step of the
algorithm by using the property of the array that is sorted. It does so by comparing the mid value
in the search space to the target value. If the target value matches the middle element, its
position in the array is returned else it discards half of the search space based on the comparison
result.
Let us track the search space by using two index –start and end. Initially start = 0, and
end = n-1. At each step, we find the mid value in the search space and compares it with target
value. There three cases possible:
Case 1: if target = A[mid], we return mid.
Case 2: if target < A[mid], we discard all elements in the right search space
including the mid element
i.e. A[mid….high]. now our new high would be mid-1.
Case 3: if target > A[mid], we discard all elements in the left search space
including the mid element
i.e. A[low…mid]. Now our new low would be mid+1.
We repeat the process until target is found or our search space is exhausted. Let’s understand this by taking
an example.
Let arr = {2, 3, ,5 ,7 ,8, 10, 12, 15, 18, 20}
target = 7
Binary Search Algorithm
public class BinarySearch
{
// find out if a key x exists in the sorted array A
// or not using binary search algorithm
public static int binarySearch(int[] A, int x)
{
// search space is A[left..right]
int left = 0, right = A.length - 1;
if (index != -1) {
System.out.println("Element found at index " + index);
} else {
System.out.println("Element not found in the array");
}
}
}