Linear Search With an Example
Subject: PPS (Programming for Problem Solving)
Contributed By: Sanjay
Created At: February 3, 2025
Question:
Explain Linear Search with an Example in depth.
Explanation Video:

Explanation:
Linear Search Procedure
Linear search is a simple searching algorithm that checks each element in an array sequentially until the desired element is found. If the element is found, its index is returned; otherwise, it indicates that the element is not in the array.
Steps of Linear Search:
Start from the first element of the array.
Compare each element with the target (search key).
If a match is found, return the index of that element.
If the end of the array is reached and no match is found, return -1 (indicating the element is not in the array)
Dry Run of Linear Search
Given Array:
arr = [10, 20, 30, 40, 50]
Search key = 30
Step-by-Step Execution:
Start from index 0. The element is 10. Since 10 ≠ 30, move to the next index.
At index 1, the element is 20. Since 20 ≠ 30, move to the next index.
At index 2, the element is 30. Since 30 = 30, the search is successful, and we return index 2.
The search stops since we found the key.
Final Result:
The element 30 is found at index 2.
If the key was 60, we would check all elements and conclude that the element is not found.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int key = 30, n = sizeof(arr) / sizeof(arr[0]), found = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
printf("Element found at index %d\n", i);
found = 1;
break;
}
}
if (!found)
printf("Element not found\n");
return 0;
}
Element found at index 2