Saturday, August 20, 2011

Program to search an element in array using Binary search.

//Program to search an element in array using Binary search.
#include<stdio.h>
#include<conio.h>
void main()
{
 int *a,i,n,b,e,m,num,loc=-1;
 clrscr();
 printf("Enter the number of elements in the array u want:");
 scanf("%d",&n);
 a=(int *) malloc(n*sizeof(int));
 printf("Enter the value of elements! please make sure that list should be sorted");
 for(i=0;i<n;i++)
 {
 printf(" enter the values of %d elements: ",i);
   scanf("%d",&a[i]);
 }
 b=0;
 e=n-1;
 printf("\n enter the requried element");
 scanf("%d",&num);
 while(b<=e&&loc==0)
 {
  m=(b+e)/2;
  if(a[m]==num)
  {
    loc=m;
  }
  else
  {
   if(a[m]>num)
   {
    e=m-1;
   }
   else
   {
    b=m+1;
   }
  }
 }
 if(loc==-1)
 printf("\n element is not found");
 else
 printf("element found at location %d: ",loc);
 getch();
}

Previous Next Home
0 Comments
Comments

Leave a Comment

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Twitter Delicious Facebook Favorites More