Saturday, April 2, 2011

Btree Implementation

#include<iostream>
using namespace std;
template<class T,int m>
class bnode
{
   public:
          int no;                       //total no of keys
          T key[m-1];    
          bnode<T,m> *ptr[m];
          bool leaf;                  //whether its a leaf node or not
       bnode()
        {
           for(int j=0;j<m;j++)
             key[j]=-1;
             leaf=1;
             no=0;
        }
    ~bnode()
     {
         //delete the node
        }
 };
 template<class T,int m>
 class btree
 {
    public:
           bnode<T,m> *root;
         btree()
          {
             bnode<T,m> *root=new bnode<T,m>;
          }
     ~btree()
          { //delete the tree}
       void create();
       void insert(T k);
       void split_child(bnode<T,m> *par,int i,bnode<T,m> *child);
       void insert_nonfull(bnode<T,m> *par,T k);
 };
 template<class T,int m>
 void btree<T,m> ::create()
 {
    bnode<T,m> *z=new bnode<T,m>;
    z->leaf=1;
    z->no=0;
    root=z;
 }
 template<class T,int m>
void btree<T,m>:: insert(T k)
{
  bnode<T,m> *s,*r;
  r=root;
  if(r->no==m-1)
   {
      s=new bnode<T,m>;
      s->leaf=0;
      s->no=0;
      s->ptr[0]=r;
      split_child(s,0,r);
      insert_nonfull(s,k);
   }
  else
    insert_nonfull(s,k);
 }
 template<class T,int m>
 void btree<T,m>::split_child(bnode<T,m> *par,int i,bnode<T,m> *child) 
 {
    int j;
    bnode<T,m> *z=new bnode<T,m>;
    z->leaf=child->leaf;
    z->no=(m/2);
    for(j=0;j<(m/2);j++)
       z->key[j]=child->key[j+(m/2)];
    if(!(child->leaf))
    {
       for(j=0;j<(m/2);j++)
         z->ptr[j]=child->ptr[j+(m/2)+1];
    }
    child->no=(m/2);
    for(j=par->no;j>=i;j--)
      par->ptr[j+1]=par->ptr[j];
    par->ptr[i+1]=z;
    for(j=par->no;j>i;j--)
      par->key[j+1]=par->key[j];
     par->key[i]=child->key[m/2];
     par->no+=1;
  }
  template<class T,int m>
  void btree<T,m>::insert_nonfull(bnode<T,m> *x,T k)
  {
    int i=x->no;
    if(x->leaf)
    {
       while(i>=0&&k<x->key[i])
            x->key[i+1]=x->key[i];
         i-=1;
         x->key[i+1]=k;
         x->no+=1;
     }
     else
     {
       while(i>=0&&k<x->key[i])
          i-=1;
          i+=1;
          if(x->ptr[i]->no==m-1)
             split_child(x,i,x->ptr[i]);
          if(k>x->key[i])
            i=i+1;
          insert_nonfull(x->ptr[i],k);
     }
  }
  int main()
  {
   int x,j;
    btree<int,5> bt;
   cin>>x;
    for(int i=0;i<x;i++)
    {   
        cin>>j;
         bt.insert(j);
   }
    return 0;
  }
   
           
         
  
      
      
            

No comments:

Post a Comment