binary search

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.

  1. Compare x with the middle element.
  2. If x matches with the middle element, we return the mid index.
  3. Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half.
  4. Else (x is smaller) recur for the left half.

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 : O(min [k,logn])

we can even make the search more efficient if we perform the following steps:

Time complexity:

2i1<k<2i

therefore :

2i<2k<2i+1

and now :

i=log 2i<log(2k)=logk+log2=logk+1O(logk)

so , we find an even better way to search in a sorted array, as needed.