DSA Tutorial



LINEAR SEARCH IN DSA


📍 Linear Search in DSA

Linear Search is one of the simplest searching algorithms in Data Structures and Algorithms (DSA). It works by traversing through each element in a list and comparing it with the target value. If the element is found, its index is returned; otherwise, the search continues until the end of the list.

🔄 Process: Check each element from the start until the target element is found.

Algorithm

  • Start from the first element of the array.
  • Compare each element with the target element.
  • If found, return the index of the element.
  • If not found, continue checking the next elements.
  • If no match is found by the end of the array, return -1 indicating that the element is not in the array.

Pseudo Code

function linearSearch(arr, target):
    for i = 0 to length of arr - 1:
        if arr[i] == target:
            return i  // Element found
    return -1  // Element not found
    

💻 C Code Example

#include <stdio.h>

int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            return i;  // Element found, return index
        }
    }
    return -1;  // Element not found
}

int main() {
    int arr[] = {2, 5, 7, 9, 11, 15};
    int n = 6;
    int target = 9;
    int result = linearSearch(arr, n, target);

    if (result != -1)
        printf("Element found at index %d\n", result);
    else
        printf("Element not found\n");

    return 0;
}
    

⏱ Time Complexity

The time complexity of Linear Search is O(n), where 'n' is the number of elements in the array. In the worst case, the algorithm may need to traverse all elements in the list to find the target element.

📊 Linear Search vs. Other Searches:
- Linear Search is good for small arrays or unsorted data.
- Binary Search (O(log n)) is much faster for sorted arrays.
🚀 Try Linear Search with Your Own Example:
- Create an array of integers.
- Select a target value.
- Use the linear search algorithm to find if the target exists in the array.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review