Friday 18 October 2024

Linear search on unsorted data (No specific order among elements.)

 

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 on unsorted data (No specific order among elements.)


#include <stdio.h>


int main() {

    int A[10] = { 6, 7, 8, 9, 10,1, 2, 3, 4, 5}; // Initialize the array

    int i, x;


    printf("Enter value to search: "); // Use printf for output

    scanf("%d", &x); // Use scanf for input


    // Linear search for the value in the array

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

        if (A[i] == x) {

            break; // Break the loop if the value is found

        }

    }


    if (i == 10) //If i is 10, it means the loop completed without finding the value. 

    {

        printf("Value not found\n"); // Output if the value is not found

    } else {

        printf("Value found"); // Output the index where the value was found

    }

   return 0;

}