📊📚Intermediate

Search Element in Array (Binary Search)

Search in sorted array

Binary Search efficiently finds an element in a sorted array by repeatedly dividing the search interval in half. Time complexity: O(log n).

Program Code

binary_search.c
C
1#include <stdio.h>
2
3int binarySearch(int arr[], int n, int target) {
4 int left = 0, right = n - 1;
5
6 while (left <= right) {
7 int mid = left + (right - left) / 2;
8
9 if (arr[mid] == target)
10 return mid; // Found
11 else if (arr[mid] < target)
12 left = mid + 1; // Search right half
13 else
14 right = mid - 1; // Search left half
15 }
16 return -1; // Not found
17}
18
19int main() {
20 int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
21 int n = sizeof(arr) / sizeof(arr[0]);
22 int target;
23
24 printf("Array: ");
25 for (int i = 0; i < n; i++) printf("%d ", arr[i]);
26 printf("\n");
27
28 printf("Enter element to search: ");
29 scanf("%d", &target);
30
31 int result = binarySearch(arr, n, target);
32
33 if (result != -1)
34 printf("Found at index %d\n", result);
35 else
36 printf("Element not found\n");
37
38 return 0;
39}
Output

Array: 2 5 8 12 16 23 38 56 72 91

Enter element to search: 23

Found at index 5

Important: Binary search only works on sorted arrays. If the array is unsorted, sort it first or use linear search.

Want to Learn More?

Explore our comprehensive tutorials for in-depth explanations of C programming concepts.

Browse Tutorials
Back to All Examples