Linear Search • Binary Search • Complexity • Example Programs
When you store many values (e.g., in an array), you often need to **find whether a given value exists** — this process is called searching.
Different searching algorithms exist, each suited for different situations.
Linear search checks each element one-by-one from start to end until the target value is found.
for i = 0 to n-1:
if array[i] == target:
return i
return -1
#include <stdio.h>
int linearSearch(int a[], int n, int target) {
for (int i = 0; i < n; i++) {
if (a[i] == target)
return i;
}
return -1;
}
int main() {
int a[] = {3, 5, 2, 9, 6};
int n = 5;
int target = 9;
int idx = linearSearch(a, n, target);
if (idx != -1)
printf("Found at index %d", idx);
else
printf("Not found");
return 0;
}
Time Complexity: O(n) — checks all elements in worst case.
Binary search works only on sorted arrays. It repeatedly divides the search space in half.
Imagine you want to find the exact time when a bike was stolen using 12 hours of CCTV footage.
This is EXACTLY how binary search works — **keep cutting the search space in half**.
low = 0
high = n-1
while low ≤ high:
mid = (low + high) / 2
if array[mid] == target: return mid
if array[mid] < target: low = mid + 1
else: high = mid − 1
return -1
#include <stdio.h>
int binarySearch(int a[], int n, int target) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == target)
return mid;
else if (a[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main() {
int a[] = {2, 4, 6, 8, 10};
int n = 5;
int target = 6;
int idx = binarySearch(a, n, target);
if (idx != -1)
printf("Found at index %d", idx);
else
printf("Not found");
return 0;
}
Time Complexity: O(log n) — extremely fast.
| Situation | Method |
|---|---|
| Array unsorted | Linear Search |
| Array sorted | Binary Search |
| Small array | Linear Search |
| Large array | Binary Search |
#include <stdio.h>
int binarySearch(int a[], int n, int target) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == target)
return mid;
else if (a[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main() {
int n, target;
printf("Enter number of elements: ");
scanf("%d", &n);
int a[n];
printf("Enter %d sorted numbers: ", n);
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Enter target value: ");
scanf("%d", &target);
int idx = binarySearch(a, n, target);
if (idx != -1)
printf("Found at index %d", idx);
else
printf("Not found");
return 0;
}