Binary Search Unleashed: Solving Problems with Precision

BINARY SEARCH
 
CODE:

#include<stdio.h>

int main(){

    int i, n, target, index = -1;

    printf("Enter size of an array: ");

    scanf("%d", &n);

    int a[n];

    printf("Enter the sorted array elements: ");

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

        scanf("%d", &a[i]);

    }

    printf("The array elements are:\n");

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

        printf("%d\n", a[i]);

    }

    printf("Enter the searching element: ");

    scanf("%d", &target);

    int first = 0, last = n - 1;

    int mid;

    while(first <= last) {

        mid = (first + last) / 2;

        if(a[mid] == target) {

            index = mid;

            printf("%d is found at %dth index", target, index);

            return 0;

        } else if(a[mid] < target) {

            first = mid + 1;

        } else {

            last = mid - 1;

        }

    }

    printf("%d is not found\n", target);

    return 0;

}

OUTPUT:

CASE 1:
Enter size of an array: 3
Enter the sorted array elements: 10 20 30
The array elements are:
10
20
30
Enter the searching element: 20
20 is found at 1th index

CASE 2:
Enter size of an array: 3
Enter the sorted array elements: 10 20 300
The array elements are:
10
20
300
Enter the searching element: 12
12 is not found

Comments

Popular posts from this blog

Mastering Linear Search: Understanding the Basics