Monday 8 January 2018

Binary Search using C

//Program for Binary Search
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],flag=0,i,n,top,mid,bottom,key;
clrscr();
printf("\nEnter size of the array:");
scanf("%d",&n);
printf("\nEnter elements into the array in sorted order:");
for(i=0;i<n;i++)
 scanf("%d",&a[i]);
printf("\nEnter element to be searched:");
scanf("%d",&key);
top = 0;
bottom = n-1;
while(top <= bottom && flag == 0)
 {
  mid = (top + bottom) /2 ;
  if(a[mid] == key)
  flag = 1;
else if(key>a[mid])
  top = mid + 1;
else
  bottom = mid - 1;
}
if(flag == 1)
  printf("\nSearch element %d found at position %d",key,mid+1);
else
  printf("\nSearch element %d is not found.",key);
}

No comments:

Post a Comment