HOME

Tuesday, May 2, 2017

Binary Search

#include<stdio.h>
#include<conio.h>
void main()
{
    int a[20],size,i,j,mid,temp,value;
    printf("Enter size of array\n");
    scanf("%d",&size);
    printf("Enter %d value\n",size);
    for(i=0;i<size;i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=0;i<size-1;i++)
    {
        for(j=i+1;j<size;j++)
        {
            if(a[i]>a[j])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
    printf("\nThe list of sorted data is\n");
    for(i=0;i<size;i++)
    {
        printf("\n%d",a[i]);
    }
    printf("\nEnter value to search\n");
    scanf("%d",&value);
    i=0;
    j=size-1;
do
{
    mid=(i+j)/2;
    if(a[mid]<value)
    {
        i=mid+1;
    }
    else if(a[mid]>value)
    {
        j=mid-1;
    }

}while(a[mid]!=value && i<=j);
if(a[mid]==value)
{
    printf("value found");
}
else
{
    printf("value not found");
}
}


No comments:

Post a Comment