Flipkart.com

Sunday 29 April 2012

Binary and Linear Search Program


//-----------------------------------------------------------//
//           Program for Binary & Linear Search              //
//                Coded by: Subhajit Kundu                   //
//-----------------------------------------------------------//

#include<conio.h>
#include<stdio.h>
#include<iostream.h>

class search
{
int arr[50],num,key,loc,lb,ub,mid,x;
int flag;
public:
 void linear(); //decleration member function
 void binary();
};

void search::linear() //definition of member function
{
loc=-1;
 cout<<"Enter how many you want: ";
 cin>>num;
 cout<<"Enter the element: ";
 for(int i=0;i<num;i++)
 cin>>arr[i];
 cout<<"Enter the no for search: ";
 cin>>key;
 for(i=0;i<num;i++)
 {
  if(arr[i]==key)
  {
   loc=i;
   break;
   }
 }
  if(loc==-1)
  cout<<"Element not found"<<endl;
  else
    {
   cout<<"Element found at position: " <<loc;
    }
   cout<<"\nPress any key to continue:";
    getch();

        // break;

}  //close linear function

void search::binary()
{
 loc=0;flag=-1;
 cout<<"Enter how many you want: ";
 cin>>num;
 cout<<"Enter the element in ascending order: ";
        for(int i=0;i<num;i++)
 cin>>arr[i];
 cout<<"Enter the no for search: ";
 cin>>key;
 lb=0;
 ub=num-1;
 while(lb<=ub)
 {
  mid=(lb+ub)/2;
  if(arr[mid]==key)
  {
   loc=mid;
   flag=1;
   break;
  }
  if(key<arr[mid])
  ub=mid-1;
  if(key>arr[mid])
  lb=mid+1;
 }
 if(flag==-1)
 cout<<"Element not found: ";
 else
 {
  cout<<"\nElement found at position: "<<loc;
 }
   cout<<"\nPress any key to continue:";
 getch();
 }  //end of binary function.


 void main()
 {
 search s;    //object creation
 int x;
 clrscr();
 do
 {
  clrscr();
  cout<<"==========MENU=========="<<endl;
  cout<<"1. Linear search"<<endl;
  cout<<"2. Binary search"<<endl;
  cout<<"3. Exit"<<endl;
  cout<<"Enter your choice: ";
  cin>>x;
  switch(x)
  {
   case 1: s.linear();
    break;
   case 2: s.binary();
    break;
   default: cout<<"\nWrong choice try again.";
  }
 } while(x!=3);
 }

If you like the post please do suscribe us and like us on Facebook, also follow us on twitter.

1 comment:

IHT