Binary Search in C

Binary Search is a search algorithm that finds the position of a target element within a sorted list. Binary search compares the target element to the middle element in the list. If it is greater than the target element, the search continues on the remaining half of the above first half or if it lesser than the target, the search continues on the remaining half of the below first half of the list. The search process is repeated until the target is found or entire list is searched. It is also known as half interval search or binary chop.

Below coding is the program to find the element from the list of arrays in C using the Binary search.

#include<stdio.h>
#include<conio.h>
void main()
{
 int h,l,mid,n,m,flag=0,i,a[30],t,j;
 clrscr();
 printf("\n\nEnter the no of terms: ");
 scanf("%d",&n);
 printf("\n\nEnter the elements:\n");
 for(i=0;i<n;i++)
   scanf("%d",&a[i]);
 printf("\n\nEnter the number to search: ");
 scanf("%d",&m);
 for(i=0;i<n-1;i++)
 {
 for(j=0;j<n-1;j++)
 {
  if(a[j+1]<a[j])
  {
   t=a[j];
   a[j]=a[j+1];
   a[j+1]=t;
  }
 }
}
 l=0;h=n;
 while(l<=h)
 {
  mid=(l+h)/2;
  if(m>a[mid])
  {
    l=mid+1;
  }
  else if(m<a[mid])
  {
    h=mid-1;
  }
  else
  {
   flag=mid;
   break;
  }
 }
 if(flag!=0)
  printf("\nSearch found");
 else
   printf("\n\nSearch NOT found");
 getch();
}

 

Leave a Reply