Linear Search Algorithm in CPP

1. Introduction

Linear Search, also known as a sequential search, is a straightforward search algorithm. The primary idea is to traverse the array elements sequentially and compare each element with the desired value. If a match is found, the search stops, and the element's position is returned. If the search completes without finding the value, it indicates that the element does not exist in the array.

2. Implementation Steps

1. Start from the first element of the array.

2. Compare the current element with the desired value.

3. If the element matches the desired value, return its index.

4. If the end of the array is reached without a match, return an indicator that the value is not found (commonly -1).

3. Implementation in C++ Programming

#include<iostream>
#include<vector>
int linearSearch(const std::vector<int>& arr, int x) {
    int n = arr.size();
    // Traverse the array
    for (int i = 0; i < n; i++) {
        // Check if the current element matches the desired value
        if (arr[i] == x) {
            return i; // Return the index of the matched value
        }
    }
    return -1; // Return -1 if the value is not found
}
int main() {
    std::vector<int> arr = {2, 4, 6, 8, 10};
    int x = 6;
    int result = linearSearch(arr, x);
    if (result != -1) {
        std::cout << "Element " << x << " is present at index " << result << std::endl;
    } else {
        std::cout << "Element " << x << " is not present in the array." << std::endl;
    }
    return 0;
}

Output:

Element 6 is present at index 2

Explanation:

1. The linearSearch function begins by accepting the array and the value to search for as arguments.

2. It then traverses the array from the beginning to the end.

3. For each element in the array, it compares the element to the desired value (x). If a match is found, the function immediately returns the index of that element.

4. If the function traverses the entire array without finding the value, it returns -1 to indicate that the value is not present in the array.


Comments