The Wayback Machine - https://web.archive.org/web/20240726084428/https://www.geeksforgeeks.org/c-program-for-binary-search-recursive-and-iterative/
Open In App

C Program for Binary Search

Last Updated : 26 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

In this article, we will understand the Binary search algorithm and how to write binary search programs in C. We will see both iterative and recursive approaches and how binary search is able to reduce the time complexity of the search operation as compared to linear search.

What is Binary Search?

Binary Search is an interval searching algorithm used to search for an item in the sorted list. It works by repeatedly dividing the list into two equal parts and then searching for the item that is the part where it can possibly exist.

Unlike linear search, there are a few conditions for applying binary search:

  1. The list must be sorted.
  2. Random access to the list member.

It means that we cannot apply the binary search in unsorted or liked data structures.

Algorithm for Binary Search in C

Let x     be the element we are searching for and the array is sorted in the ascending order.

  1. Compare x     with the middle element of the array.
     
  2. If x     matches with the middle element, we return the index of the middle element.
     
  3. Else if x     is greater than the middle element, it means that x     can only lie in the right half subarray after the middle element. So we repeat steps 1 and 2 for the right half subarray and leave the left half subarray from the algorithm
     
  4. Else if x     is smaller than the middle element, it means that x     can only lie in the left half subarray before the middle element. So, we repeat steps 1 and 2 for the left half subarray.
     
  5. We will keep doing that till we find x     or there is no element left in the subarray being considered.

As we can see, the binary search ignores the half elements of the subarray after each pass. Due to this, it is able to reduce the time required for searching the element in the array as compared to linear search.

Binary Search Program in C (Recursive)

The following C program implements the binary search algorithm using recursion:

C

// C program to implement binary search using recursion
#include <stdio.h>
 
// A recursive binary search function. It returns location
// of x in given array arr[l..r] if present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
    // checking if there are elements in the subarray
    if (r >= l) {
 
        // calculating mid point
        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;
}
 
// driver code
int main(void)
{
    // taking a sorted array
    int arr[] = { 2, 3, 4, 10, 40 };
    int size = sizeof(arr) / sizeof(arr[0]);
    // element to be searched
    int x = 10;
    // calling binary search
    int index = binarySearch(arr, 0, size - 1, x);
 
    if (index == -1) {
        printf("Element is not present in array");
    }
    else {
        printf("Element is present at index %d", index);
    }
 
    return 0;
}

                    

Output
Element is present at index 3



Complexity Analysis of Binary Search(Recursive)

Time Complexity: O(log n)
Auxiliary Space: O(log n), where n is the number of elements in the array.

Binary Seach Program in C (Iterative)

C

// C Program to implement binary search using iteration
#include <stdio.h>
 
// A iterative binary search function. It returns location
// of x in given array arr[l..r] if present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
    // the loop will run till there are elements in the
    // subarray as l > r means that there are no elements to
    // consider in the given subarray
    while (l <= r) {
 
        // calculating mid point
        int m = l + (r - l) / 2;
 
        // Check if x is present at mid
        if (arr[m] == x) {
            return m;
        }
 
        // If x greater than ,, ignore left half
        if (arr[m] < x) {
            l = m + 1;
        }
 
        // If x is smaller than m, ignore right half
        else {
            r = m - 1;
        }
    }
 
    // if we reach here, then element was not present
    return -1;
}
 
// driver code
int main(void)
{
    // creating a sorted array
    int arr[] = { 2, 3, 4, 10, 40 };
    int size = sizeof(arr) / sizeof(arr[0]);
    // element to be searched
    int x = 24;
 
    // calling binary search
    int result = binarySearch(arr, 0, size - 1, x);
 
    if (result == -1) {
        printf("Element is not present in array");
    }
    else {
        printf("Element is present at index %d", result);
    }
 
    return 0;
}

                    

Output
Element is not present in array



Complexity Analysis of Binary Search (Iterative)

Time Complexity: O(log n), where n is the number of elements in the array.
Auxiliary Space: O(1)

Please refer complete article on Binary Search for more details!



Previous Article
Next Article

Similar Reads

Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Interpolation search vs Binary search
Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Sea
7 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Why is Binary Search preferred over Ternary Search?
The following is a simple recursive Binary Search function in C++ taken from here. C/C++ Code // CPP program for the above approach #include &lt;bits/stdc++.h&gt; using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x)
11 min read
What is the difference between Binary Search and Jump Search?
Binary Search and Jump Search are two popular algorithms used for searching elements in a sorted array. Although they both try to identify a target value as quickly as possible, they use distinct approaches to get there. In this article, we will discuss the difference between binary search and jump search. Let's explore how these algorithms optimiz
2 min read
Is ternary search faster than binary search?
Binary search is a widely used algorithm for searching a sorted array. It works by repeatedly dividing the search space in half until the target element is found. Ternary search is a variation of binary search that divides the search space into three parts instead of two. This article explores the performance comparison between ternary search and b
3 min read
Which is faster between binary search and linear search?
In computer science, search algorithms are used to locate a specific element within a data structure. Two commonly used search algorithms are binary search and linear search. Understanding their relative speeds is crucial for optimizing search operations. Let's compare the speed of Binary Search and Linear Search to determine which one is faster. B
2 min read
Is there any search faster than Binary Search?
No, there is no search faster than Binary Search. Binary Search is the fastest searching algorithm for sorted data. It takes O(log2N) time to search any element in the sorted search space. In this article, we will discuss about how Binary Search works, it time complexity, comparison with other search algorithms, etc. How Does Binary Search Work?Bin
3 min read
three90RightbarBannerImg