How to do Linear Search in an Array?

Data Structure >   Searching >   Linear Search  

Short Question

475


Answer:

Linear search or Sequential is the simplest search algorithm for finding a particular value in an array, that consists of checking every one of its elements, one at a time and in sequence until the desired one is found.

Here's an example code for performing a linear search in an array using C language:


#include <stdio.h>

// Function to perform linear search in an array
int linearSearch(int arr[], int n, int key) {
    int i;
    for (i = 0; i < n; i++) {
        if (arr[i] == key)
            return i;
    }
    return -1;
}

int main() {
    int arr[] = { 2, 5, 7, 12, 16, 20, 23 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int key = 16;

    int index = linearSearch(arr, n, key);

    if (index == -1) {
        printf("Element not found in array");
    } else {
        printf("Element found at index %d", index);
    }

    return 0;
}

In this code, we have defined a function linearSearch which takes an integer array, its size and the search key as arguments. The function then iterates through the array elements one by one and compares them with the search key. If the key is found, the function returns the index of the key in the array, otherwise it returns -1 indicating that the key was not found.

In the main function, we have declared an integer array, its size and the search key. We then call the linearSearch function passing these arguments, and store the result in the index variable. We then check if the value of index is -1 or not, and print the appropriate message indicating whether the key was found or not.


This Particular section is dedicated to Question & Answer only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.