Searching Algorithms in C (Complete Guide with Examples)
This tutorial explains searching algorithms in C, which are used to find an element in a data structure. It covers Linear Search and Binary Search with practical examples, helping improve problem-solving and algorithmic skills.
1. What is Searching
- Searching is the process of finding the position of an element in a data structure
- Common types of searching:
- Linear Search – Sequentially check each element
- Binary Search – Efficient search in sorted data using divide and conquer
2. Linear Search
- Traverse the array one by one until the element is found
- Works on both sorted and unsorted arrays
Example: Linear Search
#include <stdio.h>
int linearSearch(int arr[], int n, int key) {
for(int i = 0; i < n; i++) {
if(arr[i] == key)
return i; // element found at index i
}
return -1; // element not found
}
int main() {
int arr[] = {5, 2, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
int key = 9;
int result = linearSearch(arr, n, key);
if(result != -1)
printf("Element %d found at index %d\n", key, result);
else
printf("Element not found\n");
return 0;
}
Output:
Element 9 found at index 2
3. Binary Search
- Works on sorted arrays only
- Repeatedly divides the array into two halves and compares with mid element
Example: Binary Search
#include <stdio.h>
int binarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1;
while(low <= high) {
int mid = low + (high - low)/2;
if(arr[mid] == key)
return mid;
else if(arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1; // element not found
}
int main() {
int arr[] = {1, 2, 5, 5, 9};
int n = sizeof(arr)/sizeof(arr[0]);
int key = 5;
int result = binarySearch(arr, n, key);
if(result != -1)
printf("Element %d found at index %d\n", key, result);
else
printf("Element not found\n");
return 0;
}
Output:
Element 5 found at index 2
4. Key Points to Remember
- Linear Search: O(n), works on unsorted arrays, simple to implement
- Binary Search: O(log n), requires sorted array, very efficient for large datasets
- Always ensure array is sorted before using Binary Search
- Searching is the foundation for advanced algorithms and data structures