Binary Search in C: A Comprehensive Guide

Binary Search in C

Binary search is a widely used searching algorithm that requires the array to be sorted before search is applied. It is a divide and conquer algorithm which compares the middle element of the array with the target value, and if they are unequal, the half in which the target cannot lie is eliminated.

Key Characteristics of Binary Search

How Binary Search Works

The binary search algorithm can be divided into the following steps:

  1. Step 1: Find the middle element of the array.
  2. Step 2: If the target value is equal to the middle element of the array, return the middle element's index.
  3. Step 3: If the target value is less than the middle element, repeat the process with the left half of the array.
  4. Step 4: If the target value is greater than the middle element, repeat the process with the right half of the array.
  5. Step 5: Repeat steps 1-4 until the target value is found or the subarray reduces to zero.

Here is a simple implementation of binary search in C:

#include <stdio.h>

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
        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;
}

int main(void)
{
    int arr[] = {2, 3, 4, 10, 40};
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 10;
    int result = binarySearch(arr, 0, n - 1, x);
    (result == -1) ? printf("Element is not present in array")
                   : printf("Element is present at index %d", result);
    return 0;
}

This code will search for the number 10 in the array and output its index.

Time Complexity

The time complexity of Binary Search can be written as T(n) = T(n/2) + c. The time complexity of this algorithm is O(log n).

Conclusion

Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.

ShareTwitterShareFacebookShareLinkedin

🌻 Latest Blog Posts: Stay Informed and Inspired

Explore the latest and greatest from our blog! Dive into a diverse range of topics.

Date Conversion in PHP

Learn how to use git rebase with practical code examples. Discover the differences between rebase and merge, master interactive rebase for squashing and editing commits, and understand best practices to avoid common pitfalls.

Date Conversion in PHP

Learn how to easily convert and format dates in PHP using strtotime() and date() functions with simple code examples. Ideal for beginners.

JSON Manipulation and Conversion in PHP

Learn how to encode and decode JSON in PHP with simple examples. Master JSON manipulation using json_encode and json_decode for APIs and data transfer.

Checking for Substrings in PHP

A comprehensive guide for senior PHP engineers on how to check if a string contains a specific word using various PHP functions like strpos(), str_contains(), and preg_match().

Deleting an Element from an Array in PHP

Learn how to delete elements from arrays in PHP effectively. This comprehensive guide for senior PHP engineers covers deleting by value, by key, re-indexing, and performance considerations using functions like unset(), array_search(), array_diff(), and array_values().

TCP State Transition Diagram: A Complete Guide for Beginners

Master the TCP State Transition Diagram with this beginner-friendly guide. Learn TCP connection states, handshakes, and more!

Privacy Preferences

We and our partners share information on your use of this website to help improve your experience. For more information, or to opt out click the Do Not Sell My Information button below.