binary search geekstocode

Binary Search

In this article, we will learn how to do a binary search in an array. This is a very easy topic especially if you know the linear search technique. Let’s see more about the topic. Let’s get started!

Difficulty level: Easy

Introduction

First, we must know about the general idea of binary search. Binary search is nothing but dividing the given sorted array into two halves and then searching. Hence the name binary search!

Binary Search

Binary Search is a searching algorithm for searching an element in a sorted list or array. This Algorithm is efficient than the Linear Search algorithm and performs the search operation in logarithmic time complexity for sorted arrays or lists.

Binary Search performs the search operation by repeatedly dividing the search interval in half. The idea is, to begin with, an interval covering the whole array. 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. continuously, check until the value is found or the interval is empty.

Problem: Given a sorted array arr[] of N elements, write a function to search a given element X in arr[] using Binary Search Algorithm

Algorithm

  • Compare X with the middle element of the array.
  • If X matches with the middle element, we return the mid index.
  • 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 will now look for X in only the right half ignoring the complete left half.
  • Else if X is smaller, search for X in the left half ignoring the right half.

NOTE: To perform this binary search, the array must be sorted first.

Implementation


// A recursive binary search function. It returns 
// location of x in given array arr[l..r] if present, 
// otherwise -1 

// Initially,
// l = 0, first index of arr[].
// r = N-1, last index of arr[].
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; 
} 

An Iterative Binary Search Approach


// A iterative binary search function. It returns 
// location of x in given array arr[l..r] if present, 
// otherwise -1 

// Initially,
// l = 0, first index of arr[].
// r = N-1, last index of arr[].
int binarySearch(int arr[], int l, int r, int x) 
{ 
    while (l <= r) { 
        int m = l + (r - l) / 2; 
  
        // Check if x is present at mid 
        if (arr[m] == x) 
            return m; 
  
        // If x greater, ignore left half 
        if (arr[m] < x) 
            l = m + 1; 
  
        // If x is smaller, ignore right half 
        else
            r = m - 1; 
    } 
  
    // if we reach here, then element was 
    // not present 
    return -1; 
}

Time Complexity

O(log N), where N is the number of elements in the array.

We know that time complexity depends on the performance. So let’s see the time complexity according to the situations.

  1. Worst Case: O(log N)
  2. Best Case: O(1)
  3. Average Case: O(log N)

Space Complexity

Binary search requires three-pointers to elements, which may be array indices or pointers to memory locations. This is regardless of the array size. Therefore, the space complexity of binary search O(1). This is in the case of an iterative one.

In case of recursive implementation, O(Logn) recursion call stack space.

Practice Link – 1 LeetCode Problem Explanation

Conclusion

So in this article, we discussed what is binary search, its algorithm, and also the implementation. We also learnt about its time and space complexity and even its variations according to the conditions. Hope you learnt about the binary search of an array in an easy manner. Keep practicing to be a better coder and happy coding!!

Sudhanshu is Technology geek and also a pro pubg player. I like to create content in my free time that helps others. Currently pursuing BCA from Noida and operating Geekstocode

Leave a Comment

Your email address will not be published. Required fields are marked *