5/01/2009

C program Binary Search


/*C program Binary Search*/
#include<stdio.h>
#include<conio.h>
void main()
{
    int array[10];
    int i, j, n, temp, num;
    int low,mid,high;

    printf("Enter the value of the array\t");
    scanf("%d",&n);
    printf("Enter the elements one by one:\n");
    for(i=0; i<n; i++)
    {
        scanf("%d",&array[i]);
    }
    printf("Input array elements\n");
    for(i=0; i<n; i++)
    {
        printf("%d\n",array[i]);
    }
    for(i=0; i<n; i++)
    {
        for(j=0; j<(n-i-1); j++)
        {
            if(array[j]>array[j+1])
            {
                temp=array[j];
                array[j]=array[j+1];
                array[j+1]=temp;
            }
        }
    }
    printf("Sorted array is...\n");
    for(i=0; i<n; i++)
    {
        printf("%d\n",array[i]);
    }
    printf("Enter the element to be searched\n");
    scanf("%d",&num);
    low=1;
    high=n;
    do
    {
        mid=(low+high)/2;
        if(num<array[mid])
            high=mid-1;
        else if(num>array[mid])
            low=mid+1;
    }
    while(num!=array[mid] && low<=high);
    if(num==array[mid])
    {
        printf("\n\t%d is present at position %d",num,mid+1);
    }
    else
    {
        printf("Search is FAILED\n");
    }

}
Output:
Enter the value of the array    8
Enter the elements one by one:
4
6
1
9
7
2
3
8
Input array elements
4
6
1
9
7
2
3
8
Sorted array is...
1
2
3
4
6
7
8
9
Enter the element to be searched
5
Search is FAILED

No comments:

Post a Comment