Friday, 18 October 2024

Linear Search on Sorted Data (Elements are sorted (e.g., ascending or descending).


#include <stdio.h>


int main() {

    int A[5] = {1, 3, 5, 7, 9};  // Sorted array

    int x, i;


    printf("Enter value to search: ");

    scanf("%d", &x);


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

        if (A[i] == x) {

            printf("Value found at index %d\n", i);

            return 0;  // Exit after finding value

        } 

        else if (A[i] > x) {

            // Early termination if current element > search value

            break;

        }

    }


    printf("Value not found\n");

    return 0;

}



Dynamic array 


#include <stdio.h>


#define SIZE 5  // Define the size of the array


int main() {

    int A[SIZE];  // Declare an array of size 5

    int x, i;


    // Take array input from the user

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

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

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

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

    }


  

    while (getchar() != '\n');  // Flushes out any leftover characters


    // Take the value to search

    printf("Enter value to search: ");

    scanf("%d", &x);


    // Perform linear search with early termination

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

        if (A[i] == x) {

            printf("Value found at index %d\n", i);

            return 0;  // Exit after finding the value

        } else if (A[i] > x) {

            // Stop searching if current element is greater (array is sorted)

            break;

        }

    }


    printf("Value not found\n");

    return 0;

}