Friday, 18 October 2024

Linear Search

 

What is Linear Search?

Linear search is a simple search algorithm that looks for a specific value in a list or array by checking each element one-by-one. It continues until it finds the value or reaches the end of the list.


How Linear Search Works

  1. Start at the first element of the list.

  2. Compare each element with the target value.

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

  4. If no match is found by the end, return “not found.”


 Linear Search

#include <stdio.h>   


int linearSearch(int arr[], int target)

 {  

    int i;  

    for (i = 0; i < 5; i++) {  

        if (arr[i] == target) {  

            return i;  // Element found at index i  

        }  

    }  

    return -1;  // Element not found  

}  

  

int main() {  

    int arr[5] = {10, 2, 8, 5, 17};  

  

    int target;  // Declare target variable  


        printf("Enter the value to search: ");

    scanf("%d", &target);  // Take input from user


    int result = linearSearch(arr, target);  

    if (result == -1) {  

        printf("Element not found in the array.\n");  

    } else {  

        printf("Element found", result);  

    }  

    return 0;  

}  



Dynamic linear serach

#include <stdio.h>


#define SIZE 5  // Size of the array


// Linear search function

int linearSearch(int arr[], int target) {

    for (int i = 0; i < SIZE; i++) {

        if (arr[i] == target) {

            return i;  // Element found at index i

        }

    }

    return -1;  // Element not found

}


int main() {

    int arr[SIZE];  // Declare array


    // Take input for the array from the user

    printf("Enter %d elements:\n", SIZE);

    for (int i = 0; i < SIZE; i++) {

        printf("Element %d: ", i + 1);

        scanf("%d", &arr[i]);  // Input each element

    }


    int target;  // Declare target variable


    // Take target element input from user

    printf("Enter the value to search: ");

    scanf("%d", &target);  // Input the target value


   

    printf("You entered target: %d\n", target);


    // Perform linear search

    int result = linearSearch(arr, target);


    // Display the result

    if (result == -1) {

        printf("Element not found in the array.\n");

    } else {

        printf("Element found at index %d.\n", result);

    }


    return 0;

}