Friday, July 29, 2011

Algorithm of Searching on Tree using c/c++

A search algorithm is an algorithm that accepts an argument a and tries to find a record whose key is a.The algorithm may return the

entire record on more commonly it may return a pointer to that record.

Search in which the entire table is constantly in main memory are called internal memory.Whereas those in which most of the table is kept in auxiliary storage are called external searches.

/*
IDE : CODEBLOCKS 10.05
FILE: Search.cpp*/
#include <iostream>
using namespace std;
class seqsearch
{
     int arr[100],key,n;
     public:
     seqsearch(){n=0;}
     void insert();
     void display();
     int search();
};
void seqsearch::insert()
{
     cout<<"Enter the data to be inserted:";
     cin>>arr[n];
     n++;
}
void seqsearch::display()
{
     if(n==0) cout<<"No data to display";
     for(int i=0;i<n;i++)
          cout<<arr[i]<<'\t';
}
int seqsearch::search()
{
     cout<<"Enter the key of data to be searched:";
     cin>>key;
     for(int i=0;i<n;i++)
     {
          if(key==arr[i]) return i;
     }
     return -1;
}
int main()
{
     seqsearch a1;
     int ch;
     do
     {
          cout<<"\n*****Menu****"<<endl;
          cout<<"1.Insert data"<<endl;
          cout<<"2.Display data"<<endl;
          cout<<"3.Search data"<<endl;
          cout<<"4.Exit"<<endl;
          cout<<"Enter your choice : ";
          cin>>ch;
          switch(ch)
          {
               case 1:
                    a1.insert();
                    break;
               case 2:
                    a1.display();
                    break;
               case 3:
                    int x;x=a1.search();
                    cout<<(x+1);
                    if(x==-1) cout<<"OOPS!!Data not found";
                    else     cout<<"The data is at "
                        <<x+1<<" position";
                break;
               case 4:
                    break;
          }
    }while(ch!=4);
    return 0;
}

Drop Comment if any correction required !!!

No comments:

Post a Comment