Tuesday, 30 October 2012

Pass by reference method


Define Pass by reference method
        Ans: Pass by Reference passes in a reference to a variable- this is effectively the address of the variable into the function. This is considereably more efficient than by value and allows the function to change the variable directly, something only possible in C by passing in a pointer to the variable

Saturday, 27 October 2012

B+ trees


//C++ program to implement B-Trees
#include <iostream.h>
#include <stdlib.h>
#include <alloc.h>
const int MAX = 4 ;
const int MIN = 2 ;
struct btnode
{
int count ;
int value[MAX + 1] ;
btnode *child[MAX + 1] ;
} ;
class btree
{
private :
btnode *root ;
public :
btree( ) ;
void insert ( int val ) ;
int setval ( int val, btnode *n, int *p, btnode **c ) ;
static btnode * search ( int val, btnode *root, int *pos ) ;
static int searchnode ( int val, btnode *n, int *pos ) ;
void fillnode ( int val, btnode *c, btnode *n, int k ) ;
void split ( int val, btnode *c, btnode *n,
int k, int *y, btnode **newnode ) ;
void del ( int val ) ;
int delhelp ( int val, btnode *root ) ;
void clear ( btnode *root, int k ) ;
void copysucc ( btnode *root, int i ) ;
void restore ( btnode *root, int i ) ;
void rightshift ( int k ) ;
void leftshift ( int k ) ;
void merge ( int k ) ;
void show( ) ;
static void display ( btnode *root ) ;
static void deltree ( btnode *root ) ;
~btree( ) ;
} ;

btree :: btree( )
{
root = NULL ;
}
void btree :: insert ( int val )
{
int i ;
btnode *c, *n ;
int flag ;
flag = setval ( val, root, &i, &c ) ;
if ( flag )
{
n = new btnode ;
n -> count = 1 ;
n -> value[1] = i ;
n -> child[0] = root ;
n -> child[1] = c ;
root = n ;
}
}
int btree :: setval ( int val, btnode *n, int *p, btnode **c )
{
int k ;
if ( n == NULL )
{
*p = val ;
*c = NULL ;
return 1 ;
}
else
{
if ( searchnode ( val, n, &k ) )
cout << endl << "Key value already exists." << endl ;
if ( setval ( val, n -> child[k], p, c ) )
{
if ( n -> count < MAX )
{
fillnode ( *p, *c, n, k ) ;
return 0 ;
}
else
{
split ( *p, *c, n, k, p, c ) ;
return 1 ;
}
}
return 0 ;
}
}
btnode * btree :: search ( int val, btnode *root, int *pos )
{
if ( root == NULL )
return NULL ;
else
{
if ( searchnode ( val, root, pos ) )
return root ;
else
return search ( val, root -> child[*pos], pos ) ;
}
}
int btree :: searchnode ( int val, btnode *n, int *pos )
{
if ( val < n -> value[1] )
{
*pos = 0 ;
return 0 ;
}
else
{
*pos = n -> count ;
while ( ( val < n -> value[*pos] ) && *pos > 1 )
( *pos )-- ;
if ( val == n -> value[*pos] )
return 1 ;
else
return 0 ;
}
}
void btree :: fillnode ( int val, btnode *c, btnode *n, int k )
{
int i ;
for ( i = n -> count ; i > k ; i-- )
{
n -> value[i + 1] = n -> value[i] ;
n -> child[i + 1] = n -> child[i] ;
}
n -> value[k + 1] = val ;
n -> child[k + 1] = c ;
n -> count++ ;
}
void btree :: split ( int val, btnode *c, btnode *n,
int k, int *y, btnode **newnode )
{
int i, mid ;

if ( k <= MIN )
mid = MIN ;
else
mid = MIN + 1 ;

*newnode = new btnode ;

for ( i = mid + 1 ; i <= MAX ; i++ )
{
( *newnode ) -> value[i - mid] = n -> value[i] ;
( *newnode ) -> child[i - mid] = n -> child[i] ;
}

( *newnode ) -> count = MAX - mid ;
n -> count = mid ;

if ( k <= MIN )
fillnode ( val, c, n, k ) ;
else
fillnode ( val, c, *newnode, k - mid ) ;

*y = n -> value[n -> count] ;
( *newnode ) -> child[0] = n -> child[n -> count] ;
n -> count-- ;
}
void btree :: del ( int val )
{
btnode * temp ;

if ( ! delhelp ( val, root ) )
cout << endl << "Value " << val << " not found." ;
else
{
if ( root -> count == 0 )
{
temp = root ;
root = root -> child[0] ;
delete temp ;
}
}
}
int btree :: delhelp ( int val, btnode *root )
{
int i ;
int flag ;

if ( root == NULL )
return 0 ;
else
{
flag = searchnode ( val, root, &i ) ;
if ( flag )
{
if ( root -> child[i - 1] )
{
copysucc ( root, i ) ;
flag = delhelp ( root -> value[i], root -> child[i] ) ;
if ( !flag )
cout << endl << "Value " << val << " not found." ;
}
else
clear ( root, i ) ;
}
else
flag = delhelp ( val, root -> child[i] ) ;
if ( root -> child[i] != NULL )
{
if ( root -> child[i] -> count < MIN )
restore ( root, i ) ;
}
return flag ;
}
}
void btree :: clear ( btnode *root, int k )
{
int i ;
for ( i = k + 1 ; i <= root -> count ; i++ )
{
root -> value[i - 1] = root -> value[i] ;
root -> child[i - 1] = root -> child[i] ;
}
root -> count-- ;
}
void btree :: copysucc ( btnode *root, int i )
{
btnode *temp = root -> child[i] ;

while ( temp -> child[0] )
temp = temp -> child[0] ;

root -> value[i] = temp -> value[1] ;
}
void btree :: restore ( btnode *root, int i )
{
if ( i == 0 )
{
if ( root -> child [1] -> count > MIN )
leftshift ( 1 ) ;
else
merge ( 1 ) ;
}
else
{
if ( i == root -> count )
{
if ( root -> child[i - 1] -> count > MIN )
rightshift ( i ) ;
else
merge ( i ) ;
}
else
{
if ( root -> child[i - 1] -> count > MIN )
rightshift ( i ) ;
else
{
if ( root -> child[i + 1] -> count > MIN )
leftshift ( i + 1 ) ;
else
merge ( i ) ;
}
}
}
}
void btree :: rightshift ( int k )
{
int i ;
btnode *temp ;

temp = root -> child[k] ;

for ( i = temp -> count ; i > 0 ; i-- )
{
temp -> value[i + 1] = temp -> value[i] ;
temp -> child[i + 1] = temp -> child[i] ;
}

temp -> child[1] = temp -> child[0] ;
temp -> count++ ;
temp -> value[1] = root -> value[k] ;
temp = root -> child[k - 1] ;
root -> value[k] = temp -> value[temp -> count] ;
root -> child[k] -> child [0] = temp -> child[temp -> count] ;
temp -> count-- ;
}
void btree :: leftshift ( int k )
{
btnode *temp ;

temp = root -> child[k - 1] ;
temp -> count++ ;
temp -> value[temp -> count] = root -> value[k] ;
temp -> child[temp -> count] = root -> child[k] -> child[0] ;
temp = root -> child[k] ;
root -> value[k] = temp -> value[1] ;
temp -> child[0] = temp -> child[1] ;
temp -> count-- ;
for ( int i = 1 ; i <= temp -> count ; i++ )
{
temp -> value[i] = temp -> value[i + 1] ;
temp -> child[i] = temp -> child[i + 1] ;
}
}
void btree :: merge ( int k )
{
btnode *temp1, *temp2 ;
temp1 = root -> child[k] ;
temp2 = root -> child[k - 1] ;
temp2 -> count++ ;
temp2 -> value[temp2 -> count] = root -> value[k] ;
temp2 -> child[temp2 -> count] = root -> child[0] ;
for ( int i = 1 ; i <= temp1 -> count ; i++ )
{
temp2 -> count++ ;
temp2 -> value[temp2 -> count] = temp1 -> value[i] ;
temp2 -> child[temp2 -> count] = temp1 -> child[i] ;
}
for ( i = k ; i < root -> count ; i++ )
{
root -> value[i] = root -> value[i + 1] ;
root -> child[i] = root -> child[i + 1] ;
}
root -> count-- ;
delete temp1 ;
}
void btree :: show( )
{
display ( root ) ;
}
void btree :: display ( btnode *root )
{
if ( root != NULL )
{
for ( int i = 0 ; i < root -> count ; i++ )
{
display ( root -> child[i] ) ;
cout << root -> value[i + 1] << "\t" ;
}
display ( root -> child[i] ) ;
}
}
void btree :: deltree ( btnode *root )
{
if ( root != NULL )
{
for ( int i = 0 ; i < root -> count ; i++ )
{
deltree ( root -> child[i] ) ;
delete ( root -> child[i] ) ;
}
deltree ( root -> child[i] ) ;
delete ( root -> child[i] ) ;
}
}

btree :: ~btree( )
{
deltree ( root ) ;
}

void main( )
{
btree b ;
int arr[ ] = { 27, 42, 22, 47, 32, 2, 51, 40, 13 } ;
int sz = sizeof ( arr ) / sizeof ( int ) ;
for ( int i = 0 ; i < sz ; i++ )
b.insert ( arr[i] ) ;
cout << "B-tree of order 5:" << endl ;
b.show( ) ;
b.del ( 22 ) ;
b.del ( 11 ) ;
cout << "\n\nB-tree after deletion of values:" << endl ;
b.show( ) ;
}

Friday, 26 October 2012

HEAP SORT


#include<iostream.h>
#include<conio.h>
class heap
{
int a[20],n;
public:void read();
void create();
void heapsort();
void adjust(int);
};
void heap::read()
{
cout<<"enter elements\n";
for( int i=0;i<n;i++)
{
cin>>a[i];
}
}
void heap::heapsort()
{
int i,temp;
heapcreate(
);
for(i=n-1;i>0;i--)
{
temp=a[0];
a[0]=a[i];
a[i]=temp;
adjust(i);
}
}
void heap::create()
{
int i,j,k,item;
for(k=1;k<=n;k++)
{
item=a[k];
i=k;
j=(i-1)/2;
while(i>0 && item>a[j])
{
a[i]=a[j];
i=j;
j=(i-1)/2;
}
a[i]=item;
}
void heap::adjust(int x)
{
int i,j,k,item;
j=0;
item=a[j];
i=2*j+1;
while(i<=x-1)
{
if(i+1<=x-1)
if(a[j]<a[i+1])
i++;
if(item<a[i];
{
a[i]=a[j];
j=i;
i=2*j+1;
}
else
break;
}
a[j]=item;
}
void heap::show()
{
cout<<"sorted array is \n";
for(int i=0;i<n;i++)
{
cout<<a[i]<<"\n";
int main()
{
heap h;
int temp,i,m;
clrscr();
cout<<"enter no of elements\n";
cin>>m;
h.getdata(m);
cout<<"before sort\n";
h.show();
h.heapsort();
cout<<"after sort\n";
h.show();
getch();
return(0);
}
}

Binary Search Tree (BST)

//BINARY SEARCH TREE TRAVERSAL EXAMPLES
//EXAMPLE 1: PREORDER,INORDER POSTORDER,SEARCH


//
//binary search traversal by using recursive method
#include<iostream.h>
#include<conio.h>
#include<stdio.h>//null is macro, defined in stdio.h
template <class T>
class node
{
 node<T> * lchild;//lchild contain addrss of left child
 T data;//data field contains value
 node<T> * rchild;
 friend class tree<T>;//we can access lchild, data,rchild from tree class
//we can access lchild, data,rchild from these functions
 friend void rpreorder(node<T> *p);
 friend void rpostorder(node<T> *p);
 friend void rinorder(node<T> *p);
};

template<class T>
class tree
{
 private:
  node<T> *root;//root is a pointer to root node
 public:
   tree();
   ~tree();
  int isempty();
  void create();
  void traverse();
  void rpreorder();
  void rinorder();
  void rpostorder();
  node<t> * search(T x);
  void insert(node<T> *k);
};
template<class T>
tree<T>::tree()
{
 root=NULL;
}
template <class T>
int tree<T>::isempty()
{
 return(root==NULL);
}

//
template <class T>

void tree<T>::rpreorder(node<T> *p)
{
    if( p != NULL)
    {
        cout<<p->data);
        rpreorder(p->lchild);
        rpreorder(p->rchild);
    }
}
//rpreorder(root);
template <class T>

void tree<T>::rinorder(node<T> *p)
{
    if(p != NULL)
    {
        rinorder(p->left);
        cout<<p->data;
        rinorder(p->right);
    }
}

template <class T>

void tree<T>::rpostorder(node<T> *p)
{
    if( p != NULL)
    {
        rpostorder(p->left);
        rpostorder(p->right);
        cout<<p->data);
    }
}
template <class T>
node<T>* tree<T>::search(T x)//X IS VALUE 2 BE SEARCHD IN DA BINARY TREE
{
 node<t> *p;
 p=root;       //P POINTS TO ROOT NODE
 while(p!=NULL)//SEARCH FOR X IN THE TREE UNTIL BECOMES NULL
 {
  if(x==p->data) //IF X IS FOUND IN NODE P, RETURN ADRESS OF THT NODE
    return(p);
  else
  if(x<p->data)  //SEARCH FOR X IN LEFT SUB TREE
   p=p->lchild; // MOVE POINTER P TO LEFT CHILD
  else          //SEARCH FOR X IN THE RIGHT SUB TREE
   p=p->rchild; //MOVE POINTER TO RIGHT CHILD
 }
 return(NULL);//X IS NOT FOUND IN THE TREE
}

template<class T>
void tree<T>::insert(node,T> *k)//k is poiner to node to be inserted
{
 node<T> *p;
 if(isempty())//IF TREE IS EMPTY, NODE K IS ROOT NODE
 {
  root=k;//ROOT PTR TO THE NEW NODE
  return;//SKIP REST OF THE FUNCTION
 }
 p=root;//P POINTS TO ROOT NODE
 while(1)//ALWAYS TRUE
 {
  if(k->data<p->data)//INSERT NODE K IN THE LEFT SUB TREE
  {
   if(p->lchild!=NULL)//IF LEFT CHILD EXISTS, MOVE PTR P TO LEFTCHILD
 
    p=p->lchild;
 
   else//IF THERE IS NO LEFT CHILD, NODE K BECOMES LEFT CHILD OF P
   {
    p->lchild=k;//ATTACH NODE K AS LEFT CHILD OF P
    return;//COME OUT OF FUNCTION TO AVOID INFINITE LOOP
   }
  }
  else
  if(k-data>p->data)//INSERT NODE K IN THE RIGHT SUB TREE
  {
   if(p->rchild!=NULL)//IF RIGHT CHILD EXISTS,MOVE PTR P TO RIGHTCHILD
     p=p->rchild;
   else//IF THERE IS NO RIGHT CHILD K BECOMES RIGHT CHILD OF P
   {
    p->rchild=k;//ATTACH NODE K AS RIGHT CHILD OF P
    return;//COME OUT OF FUNCTION SOON AFTER INSERTION
   }//VALUE ALREADY EXISTS IN THE TREE
  }
  else
  {
   cout<<k->data<<"already exists. Insertion is not possible\n";
   return;
  }
}
}
}

template <class T>
void tree<T>::create()
{
 T x;
 node<T> *k;
 root=NULL;//initially tree is empty
 cout<<"ENTER VALUE TERMINATES BY -1 OR !\n";
 cin>>x;//read the 1st no's which is root node
 while(x!=-1&&x!='!')//execute loop until user types -1 or !
 {
  k=new node<T>; //create a node, k is pointer to it
  k->data=x;//store x in the new node data field
  k->lchild=k->rchild=NULL;//initially node k is leaf node
  insert(k);//isnert node k in binary tree in appropriate place
  cin>>x;//read next number
 }
}

void menu1()
{
 cout<<"1. rpreorder\n";  
 cout<<"2. rinorder\n";
 cout<<"3. rpostorder\n";
 cout<<"4. exit\n"; //levelorder() is not wrote
}

template <class T>
void tree<T>::traverse()
{
 int ch;
 clrscr();
 menu1();
 cout<<"enter ur choice\n";
 cin>>ch;
 while(ch<5)
 {
  switch(ch)
  {
   case 1: {
           rpreorder();//calling recursive() from intermediate fun
           break;
           }
   case 2: {
           rinorder();
           break;
           }
   case 3: {
           rpostorder();
           break;
           }
  }
  menu1();
  cout<<"enter ur choice\n";
  cin>>ch;
 }
}

void main()
{
 node<int> *p;
 int ch, x;
 tree<int>a;
 clrscr();
 a.create();
 clrscr();

 cout<<"enter ur choice 1. traverse \n 2. search";
 cin>>ch;
 while(ch<3)
 {
  switch(ch)
  {
    case 1: {
 //traverwse binary tree in tree, pose, inorder
//it is a intermediate function
            a.traverse();
            break;
    case 2: {
            cout<<"enter value to be searched \n";
            cin>>x;
            p=a.search(x);//it returns adres of dat node whre x is found
            if(p==NULL)
         
             cout<<"it is not found\n";
            else
              cout<,"it is found at address="<<p<<"\n";
            break;
            }
   }//switch
  cout<<"enter ur choice 1. traverse \n 2. search";
  cin>>ch;
}//while
getch();
}//


//EXAMPLE 2:




#include<iostream.h>
#include<conio.h>
#include<process.h>
class BST
{                                                              

  struct node
  {
   int data;
   node *rlink,*llink;
  };
  node *root,*temp,*n;
  public:BST()
  {
  root=NULL;
  }
  void insert(int);
  void search(int);
  void inorder(node *);
  void inordertrav();
}; // void inordertrav(int);
void BST::insert(int x)
{
  n=new node;
  n->data=x;
  n->llink=n->rlink=NULL;
  if(root==NULL)
    root=n;
  else
  {
    temp=root;
    while(temp!=NULL)
    {
     if(n->data<temp->data)
     {
       if(temp->llink!=NULL)
temp=temp->llink;
       else
       {
temp->llink=n;
temp=NULL;
       }
      }
      else
      {
       if(temp->rlink!=NULL)
temp=temp->rlink;
       else
       {
temp=n;
temp=NULL;
       }
      }
   }//outer if
 }//while
}//function
void BST::search(int s)
{
if(root==NULL)
cout<<"tree is empty"<<endl;
else
{
temp=root;
while(temp!=NULL)
{
if(s==temp->data)
{
cout<<"element found"<<endl;
break;
}
else
{
if(s<temp->data)
temp=temp->llink;
else
temp=temp->llink;
}
}
if(temp==NULL)
{
cout<<"element not found"<<endl;
}
}
}

void BST::inordertrav()
{
if(root==NULL)
{
cout<<"BST is empty"<<endl;
}
else
{
inorder(root);
}
}
void BST::inorder(node *temp)
{
inorder(temp->llink);
cout<<temp->data;
inorder(temp->rlink);
}
void main()
{
 int ch,x;
 BST b;
 clrscr();//clear
 cout<<"1.insertion\t 2.search\t 3.display(inorder)\t 4.exit\n";
 cout<<"enter ur choice\n";
 cin>>ch;
 do
 {
 switch(ch)
 {
 case 1:cout<<"enter elements\n";
 cin>>x;
 b.insert(x);
 break;
 case 2:cout<<"enter searching element\n";
 cin>>x;
 b.search(x);
 break;
 case 3:cout<<"BST elements(inorder)"<<endl;
 b.inordertrav();

 break;
 case 4:exit(0);
 }
 } while(ch<=4);
 getch();
}


BST


/* bst.cpp*/
#include<iostream.h>
#include<conio.h>
#include<process.h>

struct rec
{
long num;
struct rec *left;
struct rec *right;
};

struct rec *tree;

class ctree{
public: struct rec *delnum(long,struct rec *);
struct rec *insert(struct rec *,long);
struct rec *deletenode(long,struct rec *);
void search(struct rec *,long);
void preorder(struct rec *);
void inorder(struct rec *);
void postorder(struct rec *);
int select();
ctree()
{
tree=NULL;
}
};

void main()
{
int choice;
long digit;
int element;
ctree ct;
clrscr();
do
 {
choice=ct.select();
switch(choice)
{
  case 1: cout<<"Enter integer: To quit enter 0"<<endl;
  cin>>digit;
  while(digit!=0)
{
  tree=ct.insert(tree,digit);
  cin>>digit;
}continue;
  case 2: cout<<"Enter the number to be search";
  cin>>digit;
  ct.search(tree,digit);
  continue;
  case 3: cout<<endl<<"preorder traversing TREE";
  ct.preorder(tree);continue;
  case 4: cout<<endl<<"inorder traversing TREE";
  ct.inorder(tree);continue;
  case 5: cout<<endl<<"postorder traversing TREE";
  ct.postorder(tree);continue;
  case 6: cout<<"Enter element which do you want delete from  the BST";
   cin>>digit;
  ct.deletenode(digit,tree);continue;
  case 7: cout<<"END";
  exit(0);
}
}while(choice!=7);
}

int ctree::select()
{
int selection;
do
 {
cout<<endl<<"Enter 1: Insert a node in the BST";
cout<<endl<<"Enter 2: Search a node in BST";
cout<<endl<<"Enter 3: Display(preorder)the BST";
cout<<endl<<"Enter 4: Display(inorder)the BST";
cout<<endl<<"Enter 5: Display(postorder) the BST";
cout<<endl<<"Enter 6: Delete the element";
cout<<endl<<"Enter 7: END";
cout<<endl<<"Enter your choice ";
cin>>selection;
    if((selection<1)||(selection>7))
{
 cout<<"wrong choice:Try again";
 getch(); }
  }while((selection<1)||(selection>7));
  return (selection);
}

struct rec * ctree::insert(struct rec *tree,long digit)
{
if(tree==NULL)
 {
tree=new(struct rec);
tree->left=tree->right=NULL;
tree->num=digit;
 }
     else
 if(digit<tree->num)
tree->left=insert(tree->left,digit);
     else
 if(digit>tree->num)
tree->right=insert(tree->right,digit);
     else if(digit==tree->num)
   {
      cout<<"Duplicate node:program exited";
      exit(0);
   }
   return(tree);
}

//copy from here
struct rec * ctree::delnum(long digit,struct rec *r)
{
struct rec *q;
if(r->right!=NULL)delnum(digit,r->right);
else
q->num=r->num;
q=r;
r=r->left;
}

struct rec * ctree::deletenode(long digit,struct rec *tree)
{
struct rec *r,*q;
if(tree==NULL)
{
cout<<endl<<"Tree is empty.";
exit(0);
}
if(digit<tree->num)
deletenode(digit,tree->left);
else
if(digit>tree->num)deletenode(digit,tree->right);
q=tree;
if((q->right==NULL)&&(q->left==NULL))
q=NULL;
else
if(q->right==NULL)tree=q->left;else
if(q->left==NULL)tree=tree=q->right;else
delnum(digit,q->left);
delete(q);
}

void ctree::search(struct rec *tree,long digit)
{
if(tree==NULL)
  cout<<"The number does not exits"<<endl;
   else
if(digit==tree->num)
cout<<endl<<"Number is "<<digit;
   else
if(digit<tree->num)
  search(tree->left,digit);
   else
 search(tree->right,digit);
}

void ctree::preorder(struct rec *tree)
{
if(tree!=NULL)
 {
cout<<endl<<tree->num;
preorder(tree->left);
preorder(tree->right);
 }
}

void ctree::inorder(struct rec *tree)
{
if(tree!=NULL)
   {
inorder(tree->left);
cout<<endl<<tree->num;
inorder(tree->right);
   }
}

void ctree::postorder(struct rec *tree)
{
if(tree!=NULL)
 {
postorder(tree->left);
postorder(tree->right);
cout<<endl<<tree->num;
 }

}

/*The output of the above program is:-

Enter 1: Insert a node in the BST
Enter 2: Search a node in BST
Enter 3: Display(preorder)the BST
Enter 4: Display(inorder)the BST
Enter 5: Display(postorder) the BST
Enter 6: Delete the element
Enter 7: END
Enter your choice 1
Enter integer: To quit enter 0
82
77
90
346
0

Enter 1: Insert a node in the BST
Enter 2: Search a node in BST
Enter 3: Display(preorder)the BST
Enter 4: Display(inorder)the BST
Enter 5: Display(postorder) the BST
Enter 6: Delete the element
Enter 7: END
Enter your choice 2

Number is 35
Enter 1: Insert a node in the BST
Enter 2: Search a node in BST
Enter 3: Display(preorder)the BST
Enter 4: Display(inorder)the BST
Enter 5: Display(postorder) the BST
Enter 6: Delete the element
Enter 7: END
Enter your choice 3

preorder traversing TREE
82
77
35
90
346
Enter 1: Insert a node in the BST
Enter 2: Search a node in BST
Enter 3: Display(preorder)the BST
Enter 4: Display(inorder)the BST
Enter 5: Display(postorder) the BST
Enter 6: Delete the element
Enter 7: END
Enter your choice 4

inorder traversing TREEE
35
77
82
90
346
Enter 1: Insert a node in the BST
Enter 2: Search a node in BST
Enter 3: Display(preorder)the BST
Enter 4: Display(inorder)the BST
Enter 5: Display(postorder) the BST
Enter 6: Delete the element
Enter 7: END
Enter your choice 5

postorder traversing TREE
35
77
346
90
82
Enter 1: Insert a node in the BST
Enter 2: Search a node in BST
Enter 3: Display(preorder)the BST
Enter 4: Display(inorder)the BST
Enter 5: Display(postorder) the BST
Enter 6: Delete the element
Enter 7: END
Enter your choice 6
Enter element which do you want delete from  the BST82

Enter 1: Insert a node in the BST
Enter 2: Search a node in BST
Enter 3: Display(preorder)the BST
Enter 4: Display(inorder)the BST
Enter 5: Display(postorder) the BST
Enter 6: Delete the element
Enter 7: END
Enter your choice 7*/
------------------------------------------------------------------------------------------------------------


//binary search traversal by using recursive method
#include<iostream.h>
#include<conio.h>
#include<stdio.h>//null is macro, defined in stdio.h
template <class T>
class node
{
 node<T> * lchild;//lchild contain addrss of left child
 T data;//data field contains value
 node<T> * rchild;
 friend class tree<T>;//we can access lchild, data,rchild from tree class
//we can access lchild, data,rchild from these functions
 friend void rpreorder(node<T> *p);
 friend void rpostorder(node<T> *p);
 friend void rinorder(node<T> *p);
};
//t7(3).wav
template<class T>
class tree
{
 private:
  node<T> *root;//root is a pointer to root node
 public:
   tree();
   ~tree();
  int isempty();
  void create();
  void traverse();
  void rpreorder();
  void rinorder();
  void rpostorder();
  node<t> * search(T x);
  void insert(node<T> *k);
};
template<class T>
tree<T>::tree()
{
 root=NULL;
}
template <class T>
int tree<T>::isempty()
{
 return(root==NULL);
}

//t8(3).wav
template <class T>

void tree<T>::rpreorder(node<T> *p)
{
    if( p != NULL)
    {
        cout<<p->data);
        rpreorder(p->lchild);
        rpreorder(p->rchild);
    }
}
//rpreorder(root);
template <class T>

void tree<T>::rinorder(node<T> *p)
{
    if(p != NULL)
    {
        rinorder(p->left);
        cout<<p->data;
        rinorder(p->right);
    }
}

template <class T>

void tree<T>::rpostorder(node<T> *p)
{
    if( p != NULL)
    {
        rpostorder(p->left);
        rpostorder(p->right);
        cout<<p->data);
    }
}
template <class T>
node<T>* tree<T>::search(T x)//X IS VALUE 2 BE SEARCHD IN DA BINARY TREE
{
 node<t> *p;
 p=root;       //P POINTS TO ROOT NODE
 while(p!=NULL)//SEARCH FOR X IN THE TREE UNTIL BECOMES NULL
 {
  if(x==p->data) //IF X IS FOUND IN NODE P, RETURN ADRESS OF THT NODE
    return(p);
  else
  if(x<p->data)  //SEARCH FOR X IN LEFT SUB TREE
   p=p->lchild; // MOVE POINTER P TO LEFT CHILD
  else          //SEARCH FOR X IN THE RIGHT SUB TREE
   p=p->rchild; //MOVE POINTER TO RIGHT CHILD
 }
 return(NULL);//X IS NOT FOUND IN THE TREE
}

template<class T>
void tree<T>::insert(node,T> *k)//k is poiner to node to be inserted
{
 node<T> *p;
 if(isempty())//IF TREE IS EMPTY, NODE K IS ROOT NODE
 {
  root=k;//ROOT PTR TO THE NEW NODE
  return;//SKIP REST OF THE FUNCTION
 }
 p=root;//P POINTS TO ROOT NODE
 while(1)//ALWAYS TRUE
 {
  if(k->data<p->data)//INSERT NODE K IN THE LEFT SUB TREE
  {
   if(p->lchild!=NULL)//IF LEFT CHILD EXISTS, MOVE PTR P TO LEFTCHILD
 
    p=p->lchild;
 
   else//IF THERE IS NO LEFT CHILD, NODE K BECOMES LEFT CHILD OF P
   {
    p->lchild=k;//ATTACH NODE K AS LEFT CHILD OF P
    return;//COME OUT OF FUNCTION TO AVOID INFINITE LOOP
   }
  }
  else
  if(k-data>p->data)//INSERT NODE K IN THE RIGHT SUB TREE
  {
   if(p->rchild!=NULL)//IF RIGHT CHILD EXISTS,MOVE PTR P TO RIGHTCHILD
     p=p->rchild;
   else//IF THERE IS NO RIGHT CHILD K BECOMES RIGHT CHILD OF P
   {
    p->rchild=k;//ATTACH NODE K AS RIGHT CHILD OF P
    return;//COME OUT OF FUNCTION SOON AFTER INSERTION
   }//VALUE ALREADY EXISTS IN THE TREE
  }
  else
  {
   cout<<k->data<<"already exists. Insertion is not possible\n";
   return;
  }
}
}
}
//t8(6).wav
template <class T>
void tree<T>::create()
{
 T x;
 node<T> *k;
 root=NULL;//initially tree is empty
 cout<<"ENTER VALUE TERMINATES BY -1 OR !\n";
 cin>>x;//read the 1st no's which is root node
 while(x!=-1&&x!='!')//execute loop until user types -1 or !
 {
  k=new node<T>; //create a node, k is pointer to it
  k->data=x;//store x in the new node data field
  k->lchild=k->rchild=NULL;//initially node k is leaf node
  insert(k);//isnert node k in binary tree in appropriate place
  cin>>x;//read next number
 }
}

void menu1()
{
 cout<<"1. rpreorder\n";  
 cout<<"2. rinorder\n";
 cout<<"3. rpostorder\n";
 cout<<"4. exit\n"; //levelorder() is not wrote
}
//t8(4)
template <class T>
void tree<T>::traverse()
{
 int ch;
 clrscr();
 menu1();
 cout<<"enter ur choice\n";
 cin>>ch;
 while(ch<5)
 {
  switch(ch)
  {
   case 1: {
           rpreorder();//calling recursive() from intermediate fun
           break;
           }
   case 2: {
           rinorder();
           break;
           }
   case 3: {
           rpostorder();
           break;
           }
  }
  menu1();
  cout<<"enter ur choice\n";
  cin>>ch;
 }
}
//a.traverse();
//t10.wav(2)
void main()
{
 node<int> *p;
 int ch, x;
 tree<int>a;
 clrscr();
 a.create();
 clrscr();

 cout<<"enter ur choice 1. traverse \n 2. search";
 cin>>ch;
 while(ch<3)
 {
  switch(ch)
  {
    case 1: {
 //traverwse binary tree in tree, pose, inorder
//it is a intermediate function
            a.traverse();
            break;
    case 2: {
            cout<<"enter value to be searched \n";
            cin>>x;
            p=a.search(x);//it returns adres of dat node whre x is found
            if(p==NULL)
         
             cout<<"it is not found\n";
            else
              cout<,"it is found at address="<<p<<"\n";
            break;
            }
   }//switch
  cout<<"enter ur choice 1. traverse \n 2. search";
  cin>>ch;
}//while
getch();
}//destructor is called before object a is lost



Tuesday, 23 October 2012

graphs: BFS, DFS



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

class adj{
int i,j,c[10],graph[10][10],num,span[10][10];
public: void in();
void out();
};

void adj::in()
{
cout<<"Enter the number of nodes:-> ";
cin>>num;
cout<<"GRAPH IS REPRESENTED USING A ADJECENCY MATRIX "<<endl;

for(i=0;i<num;i++)
{
c[i]=i;
graph[i][i]=0;
for(j=i+1;j<num;j++)
{
graph[i][j]=0;

cout<<endl<<"Enter the value for edge from node "<<i<< " to "<<j<<" -> ";
cin>>graph[i][j];
graph[j][i]=graph[i][j];
}
  }
}

void adj::out()
{
   cout<<endl<<endl<<"ADJECENCY MATRIX FOR THE GRAPH IS "<<endl;
   for(i=0;i<num;i++)
  {
  cout<<endl<<(char)179;
  for(j=0;j<num;j++)
  cout<<"  "<<graph[i][j]<<"  ";
  cout<<(char)179;
  }
  for(i=0;i<num;i++)
  for(j=i;j<num;j++)
  {
  span[i][j]=0;
  if((c[i]!=c[j])&&(graph[i][j]!=0))
  {
  span[i][j]=graph[i][j];

  if(c[i]<c[j])
  c[j]=c[i];
  else
  c[i]=c[j];
  }
span[j][i]=span[i][j];
  }
   cout<<endl<<"ADJECENCY MATRIX FOR THE SPANNING TREE IS"<<endl;
  for(i=0;i<num;i++)
  {
  cout<<endl<<(char)179;
  for(j=0;j<num;j++)
  cout<<"  "<<span[i][j]<<"  ";
  cout<<(char)179;
  }

}

void main()
{
clrscr();
adj ad;
ad.in();
ad.out();
getch();
}

The output of the above program is:
Enter the number of nodes:-> 3
GRAPH IS REPRESENTED USING A ADJECENCY MATRIX
                                                                               
Enter the value for edge from node 0 to 1 -> 1                                
                                                                               
Enter the value for edge from node 0 to 2 -> 2                                
                                                                               
Enter the value for edge from node 1 to 2 -> 3                                
                                                                               
                                                                               
ADJECENCY MATRIX FOR THE GRAPH IS                                              
                                                                               
|  0    1    2  |                                                              
|  1    0    3  |                                                              
|  2    3    0  |                                                              
ADJECENCY MATRIX FOR THE SPANNING TREE IS                                      
                                                                               
|  0    1    2  |                                                              
|  1    0    0  |                                                              
|  2    0    0  |                                                              
                                                                               
                                                                               
                                                                               
                                                                               
                                                                               


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

void create();  // For creating a graph
void dfs();  // For Deapth First Search(DFS) Traversal.
void bfs();  // For Breadth First Search(BFS) Traversal.

struct node  // Structure for elements in the graph
{
   int data,status;
   struct node *next;
   struct link *adj;
};

struct link  // Structure for adjacency list
{
   struct node *next;
   struct link *adj;
};

struct node *start,*p,*q;
struct link *l,*k;

int main()
{
   int choice;
   clrscr();
   create();
   while(1)
   {
      cout<<"\n\n-----------------------";
      cout<<"\n1: DFS\n2: BSF\n3: Exit\nEnter your choice: ";
      cin>>choice;
      switch(choice)
      {
case 1:
   dfs();
   break;
case 2:
   bfs();
   break;
case 3:
   exit(0);
   break;
default:
   cout<<"\nIncorrect choice!\nRe-enter your choice.";
   getch();
      }
   }
   return 0;
}

void create()    // Creating a graph
{
   int dat,flag=0;
   start=NULL;
   cout<<"\nEnter the nodes in the graph(0 to end): ";
   while(1)
   {
      cin>>dat;
      if(dat==0)
break;
      p=new node;
      p->data=dat;
      p->status=0;
      p->next=NULL;
      p->adj=NULL;
      if(flag==0)
      {
start=p;
q=p;
flag++;
      }
      else
      {
q->next=p;
q=p;
      }
   }
   p=start;
   while(p!=NULL)
   {
      cout<<"Enter the links to "<
data<<" (0 to end) : ";
      flag=0;
      while(1)
      {
cin>>dat;
if(dat==0)
   break;
k=new link;
k->adj=NULL;
if(flag==0)
{
   p->adj=k;
   l=k;
   flag++;
}
else
{
   l->adj=k;
   l=k;
}
q=start;
while(q!=NULL)
{
   if(q->data==dat)
      k->next=q;
   q=q->next;
}
      }
      p=p->next;
   }
   cout<<"\n\n-------------------------";
   return;
}

// Deapth First Search(DFS) Traversal.
void bfs()
{
   int qu[20],i=1,j=0;
   p=start;
   while(p!=NULL)
   {
      p->status=0;
      p=p->next;
   }
   p=start;
   qu[0]=p->data;
   p->status=1;
   while(1)
   {
      if(qu[j]==0)
break;
      p=start;
      while(p!=NULL)
      {
if(p->data==qu[j])
    break;
p=p->next;
      }
      k=p->adj;
      while(k!=NULL)
      {
q=k->next;
if(q->status==0)
{
   qu[i]=q->data;
   q->status=1;
   qu[i+1]=0;
   i++;
}
k=k->adj;
      }
      j++;
   }
   j=0;
   cout<<"\n\nBreadth First Search Results\n";
   cout<<"\n---------------------------\n";
   while(qu[j]!=0)
   {
      cout<status=0;
      p=p->next;
   }
   p=start;
   stack[0]=0;
   stack[top]=p->data;
   p->status=1;
   while(1)
   {
      if(stack[top]==0)
break;
      p=start;
      while(p!=NULL)
      {
if(p->data==stack[top])
   break;
p=p->next;
      }
      cout<adj;
      while(k!=NULL)
      {
q=k->next;
if(q->status==0)
{
   top++;
   stack[top]=q->data;
   q->status=1;
}
k=k->adj;
      }
   }
   getch();
   return;
}


//a)Program to implement Breadth first Search algorithm.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int cost[10][10],i,j,k,n,queue[10],front,rear,v,visit[10],visited[10];
void main()
{
int m;
clrscr();
cout <<"enterno of vertices";
cin >> n;
cout <<"ente no of edges";
cin >> m;
cout <<"\nEDGES \n";
for(k=1;k<=m;k++)
{
cin >>i>>j;
cost[i][j]=1;
}
cout <<"enter initial vertex";
cin >>v;
cout <<"Visitied vertices\n";
cout << v;
visited[v]=1;
k=1;
while(k<n)
{
for(j=1;j<=n;j++)
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
queue[rear++]=j;
}
v=queue[front++];
cout<<v << " ";
k++;
visit[v]=0;
visited[v]=1;
}
getch();
}
//ANOTHER WAY
/*WAP TO IMPLEMENT BINARY SEARCH TREE(BST) AND ITS OPERATIONS

/*C++ program to implement Binary Search Tree(BST) and its Operations

*/

/*C++ program to implement Binary Search Tree(BST) and its Operations

*/

#include <iostream.h>

class btree

{

private :

struct node

{

node *left ;

char data ;

node *right ;

} *root ;

char *arr ;

int *lc ;

int *rc ;

public :

btree ( char *a, int *l, int *r, int size ) ;

void insert ( int index ) ;

static node* buildtree ( char *a, int *l, int *r, int index ) ;

void display( ) ;

static void inorder ( node *sr ) ;

~btree( ) ;

static void del ( node *sr ) ;

} ;

btree :: btree ( char *a, int *l, int *r, int size )

{

root = NULL ;

arr = new char[size] ;

lc = new int[size] ;

rc = new int[size] ;

for ( int i = 0 ; i < size ; i++ )

{

* ( arr + i ) = * ( a + i ) ;

* ( lc + i ) = * ( l + i ) ;

* ( rc + i ) = * ( r + i ) ;

}

}

void btree :: insert ( int index )

{

root = buildtree ( arr, lc, rc, index ) ;

}

node* btree :: buildtree ( char *a, int *l, int *r, int index )

{

node *temp = NULL ;

if ( index != -1 )

{

temp = new node ;

temp -> left = buildtree ( a, l, r, * ( l + index ) ) ;

temp -> data = * ( a + index ) ;

temp -> right = buildtree ( a, l, r, * ( r + index ) ) ;

}

return temp ;

}

void btree :: display( )

{

inorder ( root ) ;

}

void btree :: inorder ( node *sr )

{

if ( sr != NULL )

{

inorder ( sr -> left ) ;

cout << sr -> data << "\t" ;

inorder ( sr -> right ) ;

}

}

btree :: ~btree( )

{

delete arr ;

delete lc ;

delete rc ;

del ( root ) ;

}

void btree :: del ( node *sr )

{

if ( sr != NULL )

{

del ( sr -> left ) ;

del ( sr -> right ) ;

}

delete sr ;

}

void main( )

{

char a[ ] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', '\0', '\0', 'H' } ;

int  l[ ] = {  1,   3,   5,   -1,   9,  -1,  -1,   -1,   -1,  -1 } ;

int  r[ ] = {  2,   4,   6,   -1,  -1,  -1,  -1,   -1,   -1,  -1 } ;

int sz = sizeof ( a ) ;

btree bt ( a, l, r, sz ) ;

bt.insert( 0 ) ;

cout << "\nIn-order Traversal: " << endl ;

bt.display( ) ;

}



Basic Theory
Depth – first searches are performed by diving downward into a tree as quickly as possible. It does this by always generating a child node from the most recently expanded node, then generating that child’s children, and so on until a goal is found or some cutoff depth point d is reached. If a goal is not found when a leaf node is reached or at the cutoff point, the program backtracks to the most recently expanded node and generates another of its children. This process continues until a goal is found or failure occurs.
Algorithm
An algorithm for the depth – first search is the same as that for breadth first search except in the ordering of the nodes.

Place the starting node s on the top of the stack.
If the stack is empty, return failure and stop.
If the element on the stack is goal node g, return success and stop. Otherwise,
Remove and expand the first element , and place the children at the top of the stack.
Return to step 2.

Example 2:


#include<iostream.h>
#include<conio.h>
#define G 9
#define true 1
#define false 0

static int vertex[G][G]={
{0,},
{0,2,8,3},
{0,1,7,6},
{0,2,8},
{0,2,8},
{0,8,3},
{0,8,3},
{0,4,5,1,6,7}
};
int visited[G],v,w,front,rear;
int Q[G];

class bfs{
public: void AddQ(int,int[]);
void DelQ();
bfs()
{
rear=1;
front=1;
}
};

void bfs::AddQ(int v,int Q[])
{
Q[rear]=v;
rear++;
}

void bfs::DelQ()
{
front++;
if(front==G)
{
front=1;
rear=1;
}
}

void main()
{
clrscr();
bfs b;
for(v=1;v<G;v++)
visited[v]=false;
for(v=1;v<G;v++)
if(!visited[v])
{
b.AddQ(v,Q);
do
{
b.DelQ();
visited[v]=true;
for(w=1;w<G;w++)
{
if(vertex[v][w]==0)
continue;
if(!visited[vertex[v][w]])
{
visited[vertex[v][w]]=true;
b.AddQ(vertex[v][w],Q);
}
}
}while(front!=rear);
}
for(v=1;v<G;v++)
cout<<'\t'<<Q[v];
}

The output of the above program is:
1       2       8       3       4       5       6       7