Code Competitions

Coding competition

Sunday, 12 May 2013

Program to search element from a list using binary search

#include<stdio.h>
#include<conio.h>
void main()
{
    int a[20],n,i=0,d,j,k;
    clrscr();
    printf("enter the number of elements");
    scanf("%d",&n);
    printf("enter the elements in sorted order");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("enter the element to search");
    scanf("%d",&d);
    j=n;
    k=(i+j)/2;
    while(i<j)
    {
        if(a[k]==d)
        {
            printf("element is present at location %d",k+1);
            exit(0);
        }

        else if(a[k]>d)
        {
            j=k;
        }
        else
        {
            i=k;
        }
    }
    printf("number is not present in the series");
    getche();
}

No comments:

Post a Comment