Sunday 27 January 2013

Write a program to search element from array using Binary Search


#include<iostream.h>
#include<conio.h>
 void main()
 {
 int n,a[20],i,item;
 clrscr();
 cout<<"Enter the size of array :-";
 cin>>n;
 int beg=1,end=n,mid=(beg+end)/2;
 cout<<"Enter the elements of the array in sorted form :-";
 for(i=1;i<=n;i++)
            cin>>a[i];
 cout<<"\nEnter the element you  want to search:-"<<endl;
 cin>>item;
 while(a[mid]!=item && beg!=end)
             {
              if(a[mid]<item)
                        beg=mid+1;
             else
              end=mid-1;

            mid=(beg+end)/2;
             }
 if(a[mid]==item)
 cout<<"\n"<<item<<" is found at the location:- "<<mid ;
 else
 cout<<"item does not found in list";
getch();
}

1 comment: