Binary Search is one of the most efficient searching algorithms in computer science. It follows the "Divide and Conquer" approach. However, there is one strict rule: The array must be sorted before you can apply a binary search.
In the C code, we write mid = left + (right - left) / 2 instead of the simple mid = (left + right) / 2. This is a professional trick to prevent 'Integer Overflow' if the array is extremely large.
Instead of checking every single element one by one (like Linear Search), Binary Search repeatedly divides the search interval in half.
#include <stdio.h>
// Binary search function
int binarySearch(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if target is present at mid
if (arr[mid] == target)
return mid;
// If target is greater, ignore left half
if (arr[mid] < target)
left = mid + 1;
// If target is smaller, ignore right half
else
right = mid - 1;
}
// Target is not present in array
return -1;
}
int main() {
int arr[] = {2, 4, 8, 15, 23, 42, 55};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 23;
int result = binarySearch(arr, 0, n - 1, target);
if (result == -1)
printf("Element is not present in array");
else
printf("Element is present at index %d", result);
return 0;
}
Because it cuts the array size in half with every step, the time complexity is exceptionally fast.
(For example, if you have 1,000,000 sorted elements, a linear search might take 1,000,000 checks, but a binary search will find the target in a maximum of just 20 checks!)
No. Binary search fundamentally relies on the fact that the array is sorted. If the array is jumbled, you do not know which half to discard. You must sort the array first (using quicksort or mergesort) before binary searching.
How Many Rows and Columns are there in MS Excel?
Find out the exact maximum number of rows and columns in Microsoft Excel. Learn about the 1 million row limit and how the columns are named from A to XFD.
What is the Full Form of IIS in Computers?
Learn the full form of IIS in Computer Science. Understand how Microsoft's Internet Information Services works to host massive websites and web applications.
Impact Printer and Non-Impact Printer
Learn the difference between impact printers (like dot matrix) and non-impact printers (like inkjet and laser). Types, examples, and key differences explained.
What is India's First Supercomputer?
Learn about PARAM 8000, India's very first supercomputer. Discover the history of C-DAC, Vijay Bhatkar, and how India built its own supercomputer in 1991.
Difference Between Internet and Intranet
Learn the difference between the Internet (public, global network) and an Intranet (private, secure organizational network).
Turn this guide into revision flashcards, a practice exam, or an AI-generated podcast โ free, no signup required.