Tuesday, 22 August 2023

Write a program in c to implement Binary Search.

Binary Search Algorithm in C

Binary Search Algorithm in C

This code demonstrates the Binary Search algorithm in C.


#include <stdio.h>

int main()
{
    int a[5], key, flag = 0;
    int mid, first = 0, last = 4;

    printf("Enter Sorted Values::");
    for (int i = 0; i < 5; i++)
    {
        scanf("%d", &a[i]);
    }

    printf("\\nEnter Value to search:");
    scanf("%d", &key);

    mid = (first + last) / 2;

    while (first <= last)
    {
        if (a[mid] == key)
        {
            printf("\\nFound");
            break;
        }
        if (a[mid] > key)
        {
            last = mid - 1;
        }
        else
        {
            first = mid + 1;
        }
        mid = (first + last) / 2;
    }

    return 0;
}
    

This code implements the Binary Search algorithm to search for a value in a sorted array. The algorithm repeatedly divides the search interval in half until the value is found or the interval is empty.

Feel free to experiment with this code and understand how the Binary Search algorithm works!

1 comment:

  1. Output:

    Enter Sorted Values::45 69 78 144 365



    Enter Value to search:144

    ReplyDelete

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts