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.
Convert 3.5 cm x 4.5 cm to Pixels
Learn how to convert the standard passport photo size of 3.5 cm x 4.5 cm into pixels at 300 DPI for online application forms.
How to Convert 6 cm to Pixels?
Find out how many pixels are in 6 centimeters. Learn the formula using different DPI resolutions like 72, 96, and 300 for print and web design.
What is Abstraction in Java? OOP Concepts Explained
Learn what Abstraction is in Java. Understand this core OOP concept, how to use abstract classes and interfaces, and why it's crucial for hiding implementation details.
What Does a Computer Consist of? โ Components Explained
Learn what a computer consists of. CPU, input devices, output devices, memory, and storage โ all basic computer components explained for Class 6 to 10.
Advantages and Disadvantages of Computers in Daily Life
Explore the major advantages and disadvantages of computers in our daily lives. A complete list of pros and cons for school students.
Turn this guide into revision flashcards, a practice exam, or an AI-generated podcast โ free, no signup required.