Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).
Binary Search Algorithm: The basic steps to perform Binary Search are:
Illustration of Binary Search Algorithm:

Step-by-step Binary Search Algorithm: We basically ignore half of the elements just after one comparison.
class BinarySearch {
// Returns index of x if it is present in arr[l.. r], else return -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the
// middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not present
// in array
return -1;
}
}
should mention that we can run a concurrent task that perform the trivial search and binary search and the first one to find the needed element will stop both tasks.
the time complexity will be :
we can even make the search more efficient if we perform the following steps:
Time complexity:
therefore :
and now :
so , we find an even better way to search in a sorted array, as needed.