2/23/2009

C Program To Perform Binary Search


/* C Program To Perform Binary Search */
#include<stdio.h>
#include<conio.h>
int a[20],ele;
void binary(int low,int high)
{
 int mid;
 mid=(low+high)/2;

 if(mid==low && mid==high && a[mid]!=ele)
  printf("%d could not be found in the array\n",ele);
 else if(ele<a[mid])
  {
    high=mid;
    binary(low,high);
  }
 else if(ele==a[mid])
  {
    printf("%d is present at position %d",ele,mid);
  }
 else if(ele>a[mid])
  {
    low=mid+1;
    binary(low,high);
  }
}
void main()
{
 int i,j,temp,n;
 clrscr();
  printf("Enter the number of elements\n");
   scanf("%d",&n);
  printf("Enter the elements of the array\n");
  for(i=0;i<n;i++)
   scanf("%d",&a[i]);

  for(i=0;i<n;i++)
   {
   for(j=0;j<n;j++)
    {
    if(a[j]>a[j+1])
     {
       temp=a[j];
       a[j]=a[j+1];
       a[j+1]=temp;
     }
    }
   }

  printf("Sorted array is \n");
  for(i=1;i<=n;i++)
   printf("%d\n",a[i]);
  printf("Enter the element to be searched\n");
   scanf("%d",&ele);
  binary(0,n-1);
 getch();
}
Out Put:
C Program To Perform Binary Search

No comments:

Post a Comment