Monday, 27 October 2014

Binary Search

Non-Recursive C Program:

Aim:
Binary Search

Program:
#include<stdio.h>
#include<conio.h>
void main ()
{
   int A[25],i,data,flag=0,low,m,high,mid;

printf("Enter the size of array:");
scant("%d",&m);

printf("\n Enter the numbers in Ascending Order:");
  for(i=0;i<m;i++)
    {
       scanf("%d",&A[i]);
    }
printf("\n Enter the number to be search:");
scant("%d",&num);
low =0;
high = m-1;
while( low <= high )
    {
      mid = ( low+high )/2;
       if( A[mid] == data)
         {
            flag=1;
            break;
          }
       else
         {
            if( data<A[mid])
                 high = mid-1;
             else
                 low = mid+1;
           }
    }
   if( flag==1)
printf("\n Search successful, the number %d is found at %d position ",num,mid+1);
    else
printf("\nSearch unsuccessful,the number %d is not found ",num);
}

Output:
Enter the size of array : 10
Enter the numbers:
19
21
32
43
54
65
76
87
98
100
Enter the number to be search: 87
The number 87 found at 8 position.

No comments:

Post a Comment