Learn, Visualize, and Understand Linear Search Algorithm
Linear Search (also called Sequential Search) is the simplest searching algorithm. It checks each element in the array sequentially from the beginning until it finds the target value or reaches the end of the array.
Finding a book on a shelf: Imagine you're looking for a specific book on an unsorted bookshelf.
This is exactly how linear search works!
Step 1: Start from the first element (index 0)
Step 2: Compare the current element with the target value
Step 3: Decision:
arr[i] == target → Found! Return indexarr[i] != target → Move to next element (i++)Step 4: Repeat until element is found or end of array is reached
| Case | Time Complexity | Description |
|---|---|---|
| Best Case | O(1) | Element found at first position |
| Average Case | O(n) | Element found in middle |
| Worst Case | O(n) | Element at last position or not present |
| Space Complexity | O(1) | Only uses constant extra space |
Watch how linear search checks each element sequentially until it finds the target
See the C code and watch how it executes step-by-step
#include <stdio.h>
// Linear Search Function - Returns index of target element
int linearSearch(int arr[], int n, int target) {
// Iterate through each element
for (int i = 0; i < n; i++) {
printf("Checking index %d: arr[%d] = %d\\n", i, i, arr[i]);
// Check if current element matches target
if (arr[i] == target) {
printf("Match found!\\n");
return i; // Return index where element is found
}
printf("Not a match. Continue...\\n");
}
// Element not found
return -1;
}
int main() {
int arr[] = {15, 8, 23, 4, 42, 16, 30, 25};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 42;
printf("Array: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\\nSearching for: %d\\n\\n", target);
int result = linearSearch(arr, n, target);
if (result != -1) {
printf("\\n✓ Element %d found at index %d\\n", target, result);
} else {
printf("\\n✗ Element %d not found\\n", target);
}
return 0;
}