Learn, Visualize, and Understand Binary Search Algorithm
Binary Search is a highly efficient searching algorithm that works exclusively on sorted arrays. Unlike linear search which checks each element one by one, binary search divides the search space in half with each comparison, making it exponentially faster.
Dictionary Search: Imagine you're looking for the word "python" in a dictionary.
This is exactly how binary search works!
Step 1: Start with three pointers: low (start), high (end), and mid (middle)
Step 2: Calculate middle index: mid = (low + high) / 2
Step 3: Compare the target with middle element:
arr[mid] == target → Found! Return indexarr[mid] < target → Search right half (set low = mid + 1)arr[mid] > target → Search left half (set high = mid - 1)Step 4: Repeat until element is found or low > high
| Case | Time Complexity | Description |
|---|---|---|
| Best Case | O(1) | Element found at middle in first comparison |
| Average Case | O(log n) | Element found after multiple divisions |
| Worst Case | O(log n) | Element at end or not present |
| Space Complexity | O(1) | Iterative approach (O(log n) for recursive) |
Watch how binary search algorithm finds elements step-by-step with visual animations
See the C code and watch how it executes step-by-step
#include <stdio.h>
// Binary Search Function - Returns index of target element
int binarySearch(int arr[], int n, int target) {
int low = 0; // Start of search range
int high = n - 1; // End of search range
// Continue while valid search space exists
while (low <= high) {
// Calculate middle index (avoids overflow)
int mid = low + (high - low) / 2;
printf("Step: low=%d, mid=%d, high=%d | arr[%d]=%d\\n",
low, mid, high, mid, arr[mid]);
// Check if target is at middle
if (arr[mid] == target) {
return mid; // Found! Return index
}
// If target is greater, search right half
else if (arr[mid] < target) {
low = mid + 1;
printf("Target greater. Search right half.\\n\\n");
}
// If target is smaller, search left half
else {
high = mid - 1;
printf("Target smaller. Search left half.\\n\\n");
}
}
return -1; // Target not found
}
int main() {
int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 25;
printf("Array: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\\nSearching for: %d\\n\\n", target);
int result = binarySearch(arr, n, target);
if (result != -1) {
printf("\\n✓ Element %d found at index %d\\n", target, result);
} else {
printf("\\n✗ Element %d not found\\n", target);
}
return 0;
}