Binary Search


//Binary Search

#include<stdio.h>
#include<conio.h>
void main()
{
 int a[100],i,first,last,mid,n,search,c;
 clrscr();
 printf("Enter number of elements");
 scanf("%d",&n);
 printf("Enter value :");
 for(i=0;i<n;i++)
 {
  scanf("%d",&a[i]);
 }

 printf("Enter value to find\n");
 scanf("%d",&search);
 first=0;
 last=n-1;

 while(first<=last)
 {
  mid=(first+last)/2;
  if(a[mid]==search)
  {
  printf("\nValue is found");
  break;
  }
  else if(a[mid]>search)
  {
  last=mid-1;
//  break;
  }
  else if(a[mid]<search)
  {
  first=mid+1;
  }
  else
  {
  printf("Value is not found");
  break;
  }
}
  getch();
}

Post a Comment

Previous Post Next Post