Binary Search | C Program :

Write a C Program on Binary Search from user input Elements :


Concept of Binary Search:

Binary search compares the value assign before to the middle element present of the array.

How to perform Binary Search:

Whole sorted array divides repeatedly into half by comparing values in array. If the value is less than the item in the middle of the interval,the search will go the interval to the lower half. Otherwise it will do to the upper half of array.

Code: 

#include<stdio.h>
void main()
{
    int a[20],i,se,ln,u,m,l;
    printf("Enter length of array:\n");
    scanf("%d",&ln);
    printf("Enter the elements of array:\n");
    for(i=0;i<ln;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("Enter the elements to be search:\n");
    scanf("%d",&se);
    l=0;
    u=ln-1;
    while(l<=u)
    {
        m=(l+u)/2;
        if(a[m]==se)
            break;
        else if(a[m]<se)
            l=m+1;
        else
            u=m-1;
    }
    if(a[m]==se)
        printf("Yes, found at: %d\n",m+1);
    else
        printf("Search not found");
}

Output:

Comments

Popular posts from this blog

TOP 10 PROGRAMMING LANGAUAGES COMMING 2021 | ARTICLE

Write a C-program to swap two number:

Print Fibonacci Series using Recursion | C program :