Searching Algorithms in C
In the previous lesson, you learned how to arrange data using sorting algorithms.
Once data is organized, the next important task is to find a specific value from the data.
This process is called Searching.
What Is Searching?
Searching means checking whether a particular element exists in a data set.
Examples:
- Finding a roll number in a list
- Searching a contact in a phone
- Checking a value in an array
Types of Searching Algorithms
- Linear Search
- Binary Search
We will understand both clearly using C programs.
Linear Search
Linear search checks each element one by one.
It works on both sorted and unsorted data.
#include <stdio.h>
int main() {
int a[5] = {10, 25, 30, 45, 50};
int key = 30;
int i, found = 0;
for (i = 0; i < 5; i++) {
if (a[i] == key) {
found = 1;
break;
}
}
if (found)
printf("Element found at position %d", i + 1);
else
printf("Element not found");
return 0;
}
Linear search is simple but slow for large data.
Binary Search
Binary search works only on sorted data.
It repeatedly divides the search range into half.
#include <stdio.h>
int main() {
int a[5] = {10, 20, 30, 40, 50};
int key = 40;
int low = 0, high = 4, mid;
int found = 0;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) {
found = 1;
break;
}
else if (key < a[mid])
high = mid - 1;
else
low = mid + 1;
}
if (found)
printf("Element found at position %d", mid + 1);
else
printf("Element not found");
return 0;
}
Linear vs Binary Search
- Linear search is simple but slow
- Binary search is fast but needs sorted data
Real-World Example
Searching a name in:
- Unsorted list → Linear Search
- Dictionary → Binary Search
Mini Practice
- Take 10 numbers from user
- Search a number using linear search
- Then sort the array and apply binary search
Quick Quiz
Q1. What is searching?
Finding a specific element in data
Q2. Which search works on unsorted data?
Linear Search
Q3. Binary search requires what?
Sorted data
Q4. Binary search divides data into?
Two halves
Q5. Which search is faster for large data?
Binary Search