C Program for Binary Search Using Function

Subject: PPS (Programming for Problem Solving)

Contributed By: Sanjay

Created At: February 3, 2025

Question:


Write a C Program for Binary Search Using Function

Explanation Video:

Custom Image

Explanation:

 

  1. The array must be sorted before applying binary search.

  2. The function binarySearch() finds the middle element and checks whether the key is equal, smaller, or greater.

  3. The search continues in the appropriate half until the element is found or the range becomes invalid.

Source Code:
#include <stdio.h>

int binarySearch(int arr[], int low, int high, int key) {
    while (low <= high) {
        int mid = (low + high) / 2;
        if (arr[mid] == key)
            return mid;
        else if (arr[mid] < key)
            low = mid + 1;
        else
            high = mid - 1;
    }
    return -1;
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int key = 30, n = 5;
    int result = binarySearch(arr, 0, n - 1, key);

    if (result != -1)
        printf("Element found at index %d\n", result);
    else
        printf("Element not found\n");

    return 0;
}
Output:
Element found at index 2
Share this Article & Support Us:
Status
printf('Loading...');