• Courses
  • Tutorials
  • DSA
  • Data Science
  • Web Tech
May 17, 2024 |16.7K Views

Binary Search

Description
Discussion

Given a sorted array arr[] of n elements, write a function to search a given element x in arr[] and return the index of x in the array.

Consider array is 0 base index.

Examples:

Input: arr[] = {10, 20, 30, 50, 60, 80, 110, 130, 140, 170},  x = 110


Output: 6


Explanation: Element x is present at index 6. 

Binary Search Algorithm: The basic steps to perform Binary Search are:

Begin with the mid element of the whole array as a search key.


If the value of the search key is equal to the item then return an index of the search key.


Or if the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.


Otherwise, narrow it to the upper half.


Repeatedly check from the second point until the value is found or the interval is empty.


Binary Search Algorithm can be implemented in the following two ways

Iterative Method
Recursive Method

Related Article : https://www.geeksforgeeks.org/binary-search/