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:

Custom Image

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:

  1. Start from the first element of the array.

  2. Compare each element with the target (search key).

  3. If a match is found, return the index of that element.

  4. 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:

  1. Start from index 0. The element is 10. Since 10 ≠ 30, move to the next index.

  2. At index 1, the element is 20. Since 20 ≠ 30, move to the next index.

  3. At index 2, the element is 30. Since 30 = 30, the search is successful, and we return index 2.

  4. 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.

Source Code:
#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;
}
Output:
Element found at index 2
Share this Article & Support Us:
Status
printf('Loading...');