Binary Search in C – Efficient Program with Step-by-Step Logic

Searching is a crucial part of many computer algorithms. Binary search is an efficient way to search for an element in a sorted array. In this post, we’ll implement binary search in C, explain its logic, and provide a fully working C program for beginners.


Binary search is a divide-and-conquer algorithm. It repeatedly divides the search interval in half. If the value of the search key is less than the middle element, the algorithm continues in the left half. Otherwise, it continues in the right half.


Binary Search Algorithm Steps:

  1. Start with the left and right pointers.
  2. Find the middle index.
  3. If the middle element is the target, return its index.
  4. If the target is less than the middle, search in the left half.
  5. If the target is greater, search in the right half.
  6. Repeat until the element is found or the range is empty.

Binary Search in C – Full Program:

#include <stdio.h>

int binarySearch(int arr[], int size, int target) {
int left = 0, right = size - 1;

while (left <= right) {
int mid = left + (right - left) / 2;

if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}

return -1; // Not found
}

int main() {
int arr[] = {10, 20, 30, 40, 50, 60, 70};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 50;

int result = binarySearch(arr, size, target);

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

return 0;
}

  • Works on sorted arrays
  • Faster than linear search
  • Time complexity: O(log n)

Understanding binary search in C helps improve your algorithmic thinking and prepare you for interviews or competitive programming.

Previous Article

Bubble Sort in C – Step-by-Step C Program with Explanation

Next Article

SQL Experiments List, Top 12 Practical Tasks for Students

Write a Comment

Leave a Comment

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

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨