You are on page 1of 52

Aim of Program : To implement Insertion in a Binary Search Tree

#include <stdio.h>
#include <stdlib.h>

struct tree {
int data ;
struct tree * left ;
struct tree * right ;
} * root = NULL ;

struct tree * createNode ( int val ) {


struct tree * newNode = ( struct tree * ) malloc ( sizeof ( struct tree ) ) ;
newNode -> left = NULL ;
newNode -> right = NULL ;
newNode -> data = val ;
return newNode ;
}

struct tree * insert ( struct tree * node , int val ) { if (


node == NULL )
return createNode( val ) ;
if ( val < node -> data )
node -> left = insert ( node -> left , val ) ; else if
( val > node -> data )
node -> right = insert ( node -> right , val ) ; return
node ;
}

void inorder ( struct tree * node )


{
if ( node != NULL )
{
inorder ( node -> left ) ;
printf ( " %d " , node -> data )
inorder ( node -> right ) ;
}
}
void preorder ( struct tree * node )
{
if ( node != NULL )
{
printf ( " %d " , node -> data ) ;
preorder ( node -> left ) ;

1
preorder ( node -> right ) ;
}
}
void postorder ( struct tree * node )
{
if ( node != NULL )
{
postorder ( node -> left ) ;
postorder ( node -> right ) ;
printf ( " %d " , node -> data ) ;
}
}
void levelorder ( struct tree * node )
{
struct tree * queue [ 500 ] ;
int front , rear ;
queue [ 0 ] = root ;
front = 0 ;
rear = front ;
do {
if ( queue [ front ] -> left )
queue [ ++ rear ] = queue [ front ] -> left ; if (
queue [ front ] -> right )
queue [ ++ rear ] = queue [ front ] -> right ; printf
( " %d " , queue [ front ] -> data ) ; front ++ ;
} while ( front <= rear ) ;
}

int main ()
{
root = insert ( root , 7 ) ;
insert ( root , 9 ) ;
insert ( root , 4 ) ;
insert ( root , 10 ) ;
insert ( root , 16 ) ;
insert ( root , 40 ) ;
printf ( " \n INORDER TRAVERSAL \n " ) ;
inorder ( root ) ;
printf ( " \n PREORDER TRAVERSAL \n " ) ;
preorder ( root ) ;
printf ( " \n POSTORDER TRAVERSAL \n " ) ;
postorder ( root ) ;
printf ( " \n LEVELORDER TRAVERSAL \n " ) ;
levelorder ( root ) ;
return 0 ;
}

2
Output :

3
Aim of Program : To implement Deletion in a Binary Search Tree

#include<stdio.h>
#include<stdlib.h>

struct node
{
int key;
struct node *left, *right;
};
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node)); temp-
>key = item;
temp->left = temp->right = NULL;
return temp;
}

void inorder(struct node *root)


{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}

struct node* insert(struct node* node, int key)


{
if (node == NULL) return newNode(key)

if (key < node->key)


node->left = insert(node->left, key);
else
node->right = insert(node->right, key);

return node;
}

struct node * minValueNode(struct node* node)


{
struct node* current = node
while (current->left != NULL)
current = current->left;

4
return current;
}

struct node* deleteNode(struct node* root, int key)


{
if (root == NULL) return root;
if (key < root->key)
root->left = deleteNode(root->left, key);

else if (key > root->key)


root->right = deleteNode(root->right, key);

else
{
child if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left;

free(root);
return temp;
}

struct node* temp = minValueNode(root->right);

root->key = temp->key;

root->right = deleteNode(root->right, temp->key);


}
return root;
}

int main()

{
struct node *root = NULL;
root = insert(root,83);
root = insert(root,55);
root = insert(root,90);
root = insert(root,20);
root = insert(root,60);

5
root = insert(root,85);
root = insert(root,95);
printf("Inorder traversal of the given tree \n");
inorder(root);

printf("\nDelete 83");
root = deleteNode(root, 83);
printf("Inorder traversal of the modified tree \n");

inorder(root);

printf("\nDelete 20\n");
root = deleteNode(root, 20);
printf("Inorder traversal of the modified tree \n");
inorder(root);

printf("\nDelete 85\n");
root = deleteNode(root, 85);
printf("Inorder traversal of the modified tree \n");
inorder(root);

return 0;
}

Output :

6
Aim of Program : To implement Insertion in an AVL Tree

#include<stdio.h>

typedef struct node


{
int data;
struct node *left,*right;
int ht;
}node;

node *insert(node *,int);


node *Delete(node *,int);
void preorder(node *);
void inorder(node *);
int height( node *);
node *rotateright(node *);
node *rotateleft(node *);
node *RR(node *);
node *LL(node *);
node *LR(node *);
node *RL(node *);
int BF(node *);

int main()
{
node *root=NULL;
int x,n,i,op;

do
{
printf("\n1)Create:");
printf("\n2)Insert:");
printf("\n3)Delete:");
printf("\n4)Print:");
printf("\n5)Quit:");
printf("\n\nEnter Your Choice:");
scanf("%d",&op);

switch(op)
{
case 1: printf("\nEnter no. of elements:");
scanf("%d",&n);

7
printf("\nEnter tree data:");
root=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=insert(root,x);
}
break;

case 2: printf("\nEnter a data:");


scanf("%d",&x);
root=insert(root,x);
break;

case 3: printf("\nEnter a data:");


scanf("%d",&x);
root=Delete(root,x);
break;

case 4: printf("\nPreorder sequence:\n");


preorder(root);
printf("\n\nInorder sequence:\n");
inorder(root);
printf("\n");
break;
}
}while(op!=5);

return 0;
}
node * insert(node *T, int x)
{
if(T==NULL)
{
T=(node*)malloc(sizeof(node));
T->data=x;
T->left=NULL;
T->right=NULL;
}
else
if(x > T->data)
{
T->right=insert(T->right,x);
if(BF(T)==-2)
if(x>T->right->data)
T=RR(T);

8
else
T=RL(T);
}
else
if(x<T->data)
{
T->left=insert(T->left,x);
if(BF(T)==2)
if(x < T->left->data)
T=LL(T);
else
T=LR(T);
}

T->ht=height(T);

return(T);
}

node * Delete(node *T,int x)


{
node *p;

if(T==NULL)
{
return NULL;
}
else
if(x > T->data)
{
T->right=Delete(T->right,x);
if(BF(T)==2)
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
if(x<T->data)
{
T->left=Delete(T->left,x); if(BF(T)==-2)
if(BF(T->right)<=0)
T=RR(T);
else
T=RL(T);
}

9
else
{
if(T->right!=NULL)
{
p=T->right;
while(p->left!= NULL)
p=p->left;
T->data=p->data;
T->right=Delete(T->right,p->data);

if(BF(T)==2)
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
return(T->left);
}
T->ht=height(T);
return(T);
}
int height(node *T)
{
int lh,rh;
if(T==NULL)
return(0);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
if(lh>rh)
return(lh);
return(rh);
}
node * rotateright(node *x)
{
node *y;
y=x->left;
x->left=y->right;
y->right=x;
x->ht=height(x);

10
y->ht=height(y);
return(y);
}
node * rotateleft(node *x)
{
node *y;
y=x->right;
x->right=y->left;
y->left=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}

node * RR(node *T)


{
T=rotateleft(T);
return(T);
}
node * LL(node *T)
{
T=rotateright(T);
return(T);
}
node * LR(node *T)
{
T->left=rotateleft(T->left);
T=rotateright(T);
return(T);
}
node * RL(node *T)
{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}
int BF(node *T)
{
int lh,rh;
if(T==NULL)
return(0);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)

11
rh=0;
else
rh=1+T->right->ht;

return(lh-rh);
}
void preorder(node *T)
{
if(T!=NULL)
{
printf("%d(Bf=%d)",T->data,BF(T));
preorder(T->left);
preorder(T->right);
}
}
void inorder(node *T)
{
if(T!=NULL)
{
inorder(T->left);
printf("%d(Bf=%d)",T->data,BF(T));
inorder(T->right);
}
}

12
Output :

13
Aim of Program : To implement a Red-Black Tree

include<iostream>
using namespace std;

struct node
{
int key;
node *parent;
char color;
node *left;
node *right;
};
class RBtree
{
node *root;
node *q;
public :
RBtree()
{
q=NULL;
root=NULL;
}
void insert();
void insertfix(node *);
void leftrotate(node *);
void rightrotate(node *);
void del();
node* successor(node *);
void delfix(node *);
void disp();
void display( node *);
void search();
};

void RBtree::insert()
{
int z,i=0
cout<<"\nEnter key of the node to be inserted: "; cin>>z;
node *p,*q;
node *t=new node;
t->key=z;
t->left=NULL;
t->right=NULL;
t->color='r';
p=root;
q=NULL;
if(root==NULL)

14
{
root=t;
t->parent=NULL;
}
else
{
while(p!=NULL)
{
q=p;
if(p->key<t->key)
p=p->right;
else
p=p->left;
}
t->parent=q;
if(q->key<t->key)
q->right=t;
else
q->left=t;
}
insertfix(t);
}

void RBtree::insertfix(node *t)


{
node *u;
if(root==t)
{
t->color='b';
return;
}
while(t->parent!=NULL&&t->parent->color=='r')
{
node *g=t->parent->parent;
if(g->left==t->parent)
{
if(g->right!=NULL)
{
u=g->right;
if(u->color=='r')
{
t->parent->color='b';
u->color='b';
g->color='r';
t=g;
}
}
else
{
if(t->parent->right==t)
{

15
t=t->parent;
leftrotate(t);
}
t->parent->color='b';
g->color='r';
rightrotate(g);
}
}
else
{
if(g->left!=NULL)
{
u=g->left;
if(u->color=='r')
{
t->parent->color='b';
u->color='b';
g->color='r';
t=g;
}
}
else
{
if(t->parent->left==t)
{
t=t->parent;
rightrotate(t);
}
t->parent->color='b';
g->color='r';
leftrotate(g);
}
}
root->color='b';
}
}

void RBtree::del()
{
if(root==NULL)
{
cout<<"\nEmpty Tree." ;
return ;
}
int x;
cout<<"\nEnter the key of the node to be deleted: "; cin>>x;
node *p;
p=root;
node *y=NULL;
node *q=NULL;
int found=0;

16
while(p!=NULL&&found==0)
{
if(p->key==x)
found=1;
if(found==0)
{
if(p->key<x)
p=p->right;
else
p=p->left;
}
}
if(found==0)
{
cout<<"\nElement Not Found.";
return ;
}
else
{
cout<<"\nDeleted Element: "<<p->key;
cout<<"\nColour: "; if(p->color=='b')
cout<<"Black\n";
else
cout<<"Red\n"; if(p->parent!=NULL)
cout<<"\nParent: "<<p->parent->key;
else
cout<<"\nThere is no parent of the node. "; if(p->right!=NULL)
cout<<"\nRight Child: "<<p->right->key;
else
cout<<"\nThere is no right child of the node. "; if(p->left!=NULL)
cout<<"\nLeft Child: "<<p->left->key;
else
cout<<"\nThere is no left child of the node. ";
cout<<"\nNode Deleted."; if(p->left==NULL||p->right==NULL)
y=p;
else
y=successor(p);
if(y->left!=NULL)
q=y->left;
else
{
if(y->right!=NULL)
q=y->right;
else
q=NULL;
}
if(q!=NULL)
q->parent=y->parent;
if(y->parent==NULL)
root=q;
else

17
{
if(y==y->parent->left)
y->parent->left=q;
else
y->parent->right=q;
}
if(y!=p)
{
p->color=y->color;
p->key=y->key;
}
if(y->color=='b')
delfix(q);
}
}

void RBtree::delfix(node *p)


{
node *s;
while(p!=root&&p->color=='b')
{
if(p->parent->left==p)
{
s=p->parent->right;
if(s->color=='r')
{
s->color='b';
p->parent->color='r';
leftrotate(p->parent);
s=p->parent->right;
}
if(s->right->color=='b'&&s->left->color=='b')
{
s->color='r';
p=p->parent;
}
else
{
if(s->right->color=='b')
{
s->left->color=='b';
s->color='r';
rightrotate(s);
s=p->parent->right;
}
s->color=p->parent->color;
p->parent->color='b';
s->right->color='b';
leftrotate(p->parent);
p=root;
}

18
}
else
{
s=p->parent->left;
if(s->color=='r')
{
s->color='b';
p->parent->color='r';
rightrotate(p->parent);
s=p->parent->left;
}
if(s->left->color=='b'&&s->right->color=='b')
{
s->color='r';
p=p->parent;
}
else
{
if(s->left->color=='b')
{
s->right->color='b';
s->color='r';
leftrotate(s);
s=p->parent->left;
}
s->color=p->parent->color;
p->parent->color='b';
s->left->color='b';
rightrotate(p->parent);
p=root;
}
}
p->color='b';
root->color='b';

}
}
void RBtree::leftrotate(node *p)
{
if(p->right==NULL)
return ;
else
{
node *y=p->right;
if(y->left!=NULL)
{
p->right=y->left;
y->left->parent=p;
}
else
p->right=NULL;

19
if(p->parent!=NULL)
y->parent=p->parent;
if(p->parent==NULL)
root=y;
else
{
if(p==p->parent->left)
p->parent->left=y;
else
p->parent->right=y;
}
y->left=p;
p->parent=y;
}
}

void RBtree::rightrotate(node *p)


{
if(p->left==NULL)
return ;
else
{
node *y=p->left;
if(y->right!=NULL)
{
p->left=y->right;
y->right->parent=p;
}
else
p->left=NULL;
if(p->parent!=NULL)
y->parent=p->parent;
if(p->parent==NULL)
root=y;
else
{
if(p==p->parent->left)
p->parent->left=y;
else
p->parent->right=y;
}
y->right=p;
p->parent=y;
}
}

node* RBtree::successor(node *p)


{
node *y=NULL;
if(p->left!=NULL)

20
{
y=p->left;
while(y->right!=NULL)
y=y->right;
}
else
{
y=p->right;
while(y->left!=NULL)
y=y->left;
}
return y;
}

void RBtree::disp()
{
display(root);
}
void RBtree::display(node *p)
{
if(root==NULL)
{
cout<<"\nEmpty Tree.";
return ;
}
if(p!=NULL)
{
cout<<"\n\t NODE: ";
cout<<"\n Key: "<<p->key;
cout<<"\n Colour: ";
if(p->color=='b')
cout<<"Black";
else
cout<<"Red"; if(p->parent!=NULL)
cout<<"\n Parent: "<<p->parent->key;
else
cout<<"\n There is no parent of the node. ";
if(p->right!=NULL)
cout<<"\n Right Child: "<<p->right->key;
else
cout<<"\n There is no right child of the node. ";
if(p->left!=NULL)
cout<<"\n Left Child: "<<p->left->key;
else
cout<<"\n There is no left child of the node. ";
cout<<endl; if(p->left);
else
cout<<"\n\nLeft:\n"; display(p->left);
else
cout<<"\nNo Left Child.\n";*/”;
if(p->right)

21
cout<<"\n\nRight:\n"; display(p->right);
else
cout<<"\nNo Right Child.\n"*/”;
}
}

void RBtree::search()
{
if(root==NULL)
{
cout<<"\nEmpty Tree\n" ;
return ;
}
int x;
cout<<"\n Enter key of the node to be searched: "; cin>>x;
node *p=root;
int found=0;
while(p!=NULL&& found==0)
{
if(p->key==x)
found=1;
if(found==0)
{
if(p->key<x)
p=p->right;
else
p=p->left;
}
}
if(found==0)
cout<<"\nElement Not Found.";
else
{
cout<<"\n\t FOUND NODE: ";
cout<<"\n Key: "<<p->key;
cout<<"\n Colour: "; if(p->color=='b')
cout<<"Black";
else
cout<<"Red"; if(p->parent!=NULL)
cout<<"\n Parent: "<<p->parent->key;
else
cout<<"\n There is no parent of the node. ";
if(p->right!=NULL)
cout<<"\n Right Child: "<<p->right->key;
else
cout<<"\n There is no right child of the node. ";
if(p->left!=NULL)
cout<<"\n Left Child: "<<p->left->key;
else
cout<<"\n There is no left child of the node.";

22
cout<<endl;
}
}

int main()
{
int ch,y=0;
RBtree obj;
do
{
cout<<"\n\t RED BLACK TREE " ;
cout<<"\n 1. Insert in the tree ";
cout<<"\n 2. Delete a node from the tree";
cout<<"\n 3. Search for an element in the tree";
cout<<"\n 4. Display the tree ";
cout<<"\n 5. Exit " ;
cout<<"\nEnter Your Choice: "; cin>>ch;
switch(ch)
{
case 1 : obj.insert();
cout<<"\nNode Inserted.\n";
break;
case 2 : obj.del();
break;
case 3 : obj.search();
break;
case 4 : obj.disp();
break;
case 5 : y=1;
break;
default : cout<<"\nEnter a Valid Choice.";
}
cout<<endl;
}while(y!=1);
return 1;
}

23
Output :

24
Aim of Program : To implement a Splay Tree

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;

struct splay
{
int key;
splay* lchild;
splay* rchild;
};

class SplayTree
{
public:
SplayTree()
splay* RR_Rotate(splay* k2)
{
splay* k1 = k2->lchild;
k2->lchild = k1->rchild;
k1->rchild = k2;
return k1;
}

// LL(Y rotates to the left)


splay* LL_Rotate(splay* k2)
{
splay* k1 = k2->rchild;
k2->rchild = k1->lchild;
k1->lchild = k2;
return k1;
}
splay* Splay(int key, splay* root)
{
if (!root)
return NULL;
splay header;
header.lchild = header.rchild = NULL;
splay* LeftTreeMax = &header;
splay* RightTreeMin = &header;
while (1)
{

25
if (key < root->key)
{
if (!root->lchild)
break;
if (key < root->lchild->key)
{
root = RR_Rotate(root);
if (!root->lchild)
break;
}
/* Link to R Tree */
RightTreeMin->lchild = root;
RightTreeMin = RightTreeMin->lchild;
root = root->lchild;
RightTreeMin->lchild = NULL;
}
else if (key > root->key)
{
if (!root->rchild)
break;
if (key > root->rchild->key)
{
root = LL_Rotate(root);
if (!root->rchild)
break;
}
LeftTreeMax->rchild = root;
LeftTreeMax = LeftTreeMax->rchild;
root = root->rchild;
LeftTreeMax->rchild = NULL;
}
else
break;
}
LeftTreeMax->rchild = root->lchild;
RightTreeMin->lchild = root->rchild;
root->lchild = header.rchild;
root->rchild = header.lchild;
return root;
}

splay* New_Node(int key)


{
splay* p_node = new splay;
if (!p_node)
{

26
fprintf(stderr, "Out of memory!\n");
exit(1);
}
p_node->key = key;
p_node->lchild = p_node->rchild = NULL;
return p_node;
}

splay* Insert(int key, splay* root)


{
static splay* p_node = NULL;
if (!p_node)
p_node = New_Node(key);
else
p_node->key = key;
if (!root)
{
root = p_node;
p_node = NULL;
return root;
}
root = Splay(key, root
if (key < root->key)
{
p_node->lchild = root->lchild;
p_node->rchild = root;
root->lchild = NULL;
root = p_node;
}
else if (key > root->key)
{
p_node->rchild = root->rchild;
p_node->lchild = root;
root->rchild = NULL;
root = p_node;
}
else
return root;
p_node = NULL;
return root;
}

splay* Delete(int key, splay* root)


{
splay* temp;
if (!root)

27
return NULL;
root = Splay(key, root);
if (key != root->key)
return root;
else
{
if (!root->lchild)
{
temp = root;
root = root->rchild;
}
else
{
temp = root;
/*Note: Since key == root->key,
so after Splay(key, root->lchild),
the tree we get will have no right child tree.*/
root = Splay(key, root->lchild);
root->rchild = temp->rchild;
}
free(temp);
return root;
}
}

splay* Search(int key, splay* root)


{
return Splay(key, root);
}

void InOrder(splay* root)


{
if (root)
{
InOrder(root->lchild);
cout<< "key: " <<root->key;
if(root->lchild)
cout<< " | left child: "<< root->lchild->key;
if(root->rchild)
cout << " | right child: " << root->rchild->key;
cout<< "\n";
InOrder(root->rchild);
} }
};
int main()
{

28
SplayTree st;
int vector[10] = {9,8,7,6,5,4,3,2,1,0};
splay *root;
root = NULL;
const int length = 10;
int i;
for(i = 0; i < length; i++)
root = st.Insert(vector[i], root);
cout<<"\nInOrder: \n";
st.InOrder(root);
int input, choice;
while(1)
{
cout<<"\nSplay Tree Operations\n";
cout<<"1. Insert "<<endl;
cout<<"2. Delete"<<endl;
cout<<"3. Search"<<endl;
cout<<"4. Exit"<<endl;
cout<<"Enter your choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter value to be inserted: ";
cin>>input;
root = st.Insert(input, root);
cout<<"\nAfter Insert: "<<input<<endl;
st.InOrder(root);
break;
case 2:
cout<<"Enter value to be deleted: ";
cin>>input;
root = st.Delete(input, root);
cout<<"\nAfter Delete: "<<input<<endl;
st.InOrder(root);
break;
case 3:
cout<<"Enter value to be searched: ";
cin>>input;
root = st.Search(input, root);
cout<<"\nAfter Search "<<input<<endl;
st.InOrder(root);
break;

case 4:
exit(1);

29
default:
cout<<"\nInvalid type! \n";
}
}
cout<<"\n";
return 0;
}

Output :

Splay Tree Operations


1. Insert
2. Delete
3. Search
4. Exit
Enter your choice: 1
Enter value to be inserted: 1

After Insert: 1
key: 1

Splay Tree Operations


1. Insert
2. Delete
3. Search
4. Exit
Enter your choice: 1
Enter value to be inserted: 9

After Insert: 9
key: 1
key: 9 | left child: 1

------------------
(program exited with code: 1)
Press return to continue

30
Aim of Program : To implement Hash Table using Linear Probing

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
const int TABLE_SIZE = 5;
class HashNode
{
public:
int key;
int value;
HashNode(int key, int value)
{
this->key = key;
this->value = value;
}
};
class DeletedNode:public HashNode
{
private: static DeletedNode *entry;
DeletedNode():HashNode(-1, -1)
public: static DeletedNode *getNode()
{
if (entry == NULL)
entry = new DeletedNode();
return entry;
}
};
DeletedNode *DeletedNode::entry = NULL;
class HashMap
{
private:
HashNode **htable;
public:
HashMap()
{
htable = new HashNode* [TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
{
htable[i] = NULL;
}
}

31
~HashMap()
{
for (int i = 0; i < TABLE_SIZE; i++)
if (htable[i] != NULL && htable[i] != DeletedNode::getNode)
delete htable[i];
}
delete[] htable;
}
int HashFunc(int key)
{
return key % TABLE_SIZE;
}
void Insert(int key, int value)
{
int hash_val = HashFunc(key);
int init = -1;
int deletedindex = -1;
while (hash_val != init && (htable[hash_val]== DeletedNode::getNode()
||htable[hash_val]!= NULL && htable[hash_val]->key != key))
{
if (init == -1)
init = hash_val;
if (htable[hash_val] == DeletedNode::getNode())
deletedindex = hash_val;
hash_val = HashFunc(hash_val + 1);
}
if (htable[hash_val] == NULL || hash_val == init)
{
if(deletedindex != -1)
htable[deletedindex] = new HashNode(key, value);
else
htable[hash_val] = new HashNode(key, value);
}
if(init != hash_val)
{
if (htable[hash_val] != DeletedNode::getNode())
{
if (htable[hash_val] != NULL)
{
if (htable[hash_val]->key == key)
htable[hash_val]->value = value;
}
}
else
htable[hash_val] = new HashNode(key, value);
}

32
}
int Search(int key)
{
int hash_val = HashFunc(key);
int init = -1;
while (hash_val != init && (htable[hash_val]
== DeletedNode::getNode() || htable[hash_val]
!= NULL && htable[hash_val]->key != key)
{
if (init == -1)
init = hash_val;
hash_val = HashFunc(hash_val + 1);
}
if (htable[hash_val] == NULL || hash_val == init)
return -1;
else
return htable[hash_val]->value;
}
void Remove(int key)
{
int hash_val = HashFunc(key);
int init = -1;
while (hash_val != init && (htable[hash_val]
== DeletedNode::getNode() || htable[hash_val]
!= NULL && htable[hash_val]->key != key))
{
if (init == -1)
init = hash_val;
hash_val = HashFunc(hash_val + 1);
}
if (hash_val != init && htable[hash_val] != NULL)
{
delete htable[hash_val];
htable[hash_val] = DeletedNode::getNode();
}
}
};
int main()
{
HashMap hash;
int key, value;
int choice;
while(1)
{
cout<<"\n----------------------"<<endl;
cout<<"Operations on Hash Table"<<endl;

33
cout<<"\n----------------------"<<endl;
cout<<"1.Insert element into the table"<<endl;
cout<<"2.Search element from the key"<<endl;
cout<<"3.Delete element at a key"<<endl;
cout<<"4.Exit"<<endl;
cout<<"Enter your choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter element to be inserted: ";
cin>>value;
cout<<"Enter key at which element to be inserted: ";
cin>>key;
hash.Insert(key, value);
break;
case 2:
cout<<"Enter key of the element to be searched: ";
cin>>key;
if(hash.Search(key) == -1)
{
cout<<"No element found at key "<<key<<endl;
continue;
}
else
{
cout<<"Element at key "<<key<<" : ";
cout<<hash.Search(key)<<endl;
}
break;
case 3:
cout<<"Enter key of the element to be deleted: ";
cin>>key;
hash.Remove(key);
break;
case 4:
exit(1);
default:
cout<<"\nEnter correct option\n";
}
}
return 0;
}

34
Output :

----------------------
Operations on Hash Table
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 100
Enter key at which element to be inserted: 1

----------------------
Operations on Hash Table
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 300
Enter key at which element to be inserted: 3

------------------
(program exited with code: 1)
Press return to continue

35
Aim of Program : To implement Hash Table using Separate Chaining

#include<iostream>
#include <list>
using namespace std;

class Hash
{
int BUCKET; // No. of buckets

// Pointer to an array containing buckets


list<int> *table;
public:
Hash(int V); // Constructor

// inserts a key into hash table


void insertItem(int x);

// deletes a key from hash table


void deleteItem(int key);

// hash function to map values to key


int hashFunction(int x) {
return (x % BUCKET);
}

void displayHash();
};

Hash::Hash(int b)
{
this->BUCKET = b;
table = new list<int>[BUCKET];
}

void Hash::insertItem(int key)


{
int index = hashFunction(key);
table[index].push_back(key);
}

36
void Hash::deleteItem(int key)
{
// get the hash index of key
int index = hashFunction(key);

// find the key in (inex)th list


list <int> :: iterator i;
for (i = table[index].begin();
i != table[index].end(); i++) {
if (*i == key)
break;
}

// if key is found in hash table, remove it


if (i != table[index].end())
table[index].erase(i);
}

// function to display hash table


void Hash::displayHash() {
for (int i = 0; i < BUCKET; i++) {
cout << i;
for (auto x : table[i])
cout << " --> " << x;
cout << endl;
}
}

// Driver program
int main()
{
// array that contains keys to be mapped
int a[] = {15, 11, 27, 8, 12};
int n = sizeof(a)/sizeof(a[0]);

// insert the keys into the hash table


Hash h(7); // 7 is count of buckets in
// hash table
for (int i = 0; i < n; i++)
h.insertItem(a[i]);

// delete 12 from hash table


h.deleteItem(12);

// display the Hash table

37
h.displayHash();

return 0;
}

Output :

38
Aim of Program : To implement Brute-Force Pattern Searching
algorithm

#include <stdio.h>
#include <string.h>

void search(char* pat, char* txt)


{
int M = strlen(pat);
int N = strlen(txt);

/* A loop to slide pat[] one by one */


for (int i = 0; i <= N - M; i++) {
int j;

/* For current index i, check for pattern match */


for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;

if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]


printf("Pattern found at index %d \n", i);
}
}

/* Driver program to test above function */


int main()
{
char txt[] = "AABAACAADAABAAABAA";
char pat[] = "AABA";
search(pat, txt);
return 0;
}

39
Output :

40
Aim of Program : To implement KMP Pattern Searching algorithm

#include <bits/stdc++.h>

void computeLPSArray(char* pat, int M, int* lps);

// Prints occurrences of txt[] in pat[]


void KMPSearch(char* pat, char* txt)
{
int M = strlen(pat);
int N = strlen(txt);

// create lps[] that will hold the longest prefix suffix


// values for pattern
int lps[M];

// Preprocess the pattern (calculate lps[] array)


computeLPSArray(pat, M, lps);

int i = 0; // index for txt[]


int j = 0; // index for pat[]
while (i < N) {
if (pat[j] == txt[i]) {
j++;
i++;
}

if (j == M) {
printf("Found pattern at index %d ", i - j);
j = lps[j - 1];
}

// mismatch after j matches


else if (i < N && pat[j] != txt[i]) {
// Do not match lps[0..lps[j-1]] characters,
// they will match anyway
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}

41
}

// Fills lps[] for given patttern pat[0..M-1]


void computeLPSArray(char* pat, int M, int* lps)
{
// length of the previous longest prefix suffix
int len = 0;

lps[0] = 0; // lps[0] is always 0

// the loop calculates lps[i] for i = 1 to M-1


int i = 1;
while (i < M) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
// This is tricky. Consider the example.
// AAACAAAA and i = 7. The idea is similar
// to search step.
if (len != 0) {
len = lps[len - 1];

// Also, note that we do not increment


// i here
}
else // if (len == 0)
{
lps[i] = 0;
i++;
}
}
}
}

// Driver program to test above function


int main()
{
char txt[] = "ABABDABACDABABCABAB";
char pat[] = "ABABCABAB";
KMPSearch(pat, txt);
return 0;
}

42
Output :

43
Aim of Program : To implement Boyer Moore String Matching
algorithm

# include <limits.h>
# include <string.h>
# include <stdio.h>

# define NO_OF_CHARS 256

// A utility function to get maximum of two integers


int max (int a, int b) { return (a > b)? a: b; }

// The preprocessing function for Boyer Moore's


// bad character heuristic
void badCharHeuristic( char *str, int size,
int badchar[NO_OF_CHARS])
{
int i;

// Initialize all occurrences as -1


for (i = 0; i < NO_OF_CHARS; i++)
badchar[i] = -1;

// Fill the actual value of last occurrence


// of a character
for (i = 0; i < size; i++)
badchar[(int) str[i]] = i;
}

/* A pattern searching function that uses Bad


Character Heuristic of Boyer Moore Algorithm */
void search( char *txt, char *pat)
{
int m = strlen(pat);
int n = strlen(txt);

int badchar[NO_OF_CHARS];

/* Fill the bad character array by calling


the preprocessing function badCharHeuristic()
for given pattern */
badCharHeuristic(pat, m, badchar);

int s = 0; // s is shift of the pattern with

44
// respect to text
while(s <= (n - m))
{
int j = m-1;

/* Keep reducing index j of pattern while


characters of pattern and text are
matching at this shift s */
while(j >= 0 && pat[j] == txt[s+j])
j--;

/* If the pattern is present at current


shift, then index j will become -1 after
the above loop */
if (j < 0)
{
printf("\n pattern occurs at shift = %d", s);

/* Shift the pattern so that the next


character in text aligns with the last
occurrence of it in pattern.
The condition s+m < n is necessary for
the case when pattern occurs at the end
of text */
s += (s+m < n)? m-badchar[txt[s+m]] : 1;

else
/* Shift the pattern so that the bad character
in text aligns with the last occurrence of
it in pattern. The max function is used to
make sure that we get a positive shift.
We may get a negative shift if the last
occurrence of bad character in pattern
is on the right side of the current
character. */
s += max(1, j - badchar[txt[s+j]]);
}
}

/* Driver program to test above funtion */


int main()
{
char txt[] = "ABAAABCD";
char pat[] = "ABC";

45
search(txt, pat);
return 0;
}

Output :

46
Aim of Program : To implement Longest Common Subsequence
Algorithm

#include <iostream>
#include <stdlib.h>
#include <string.h>

using namespace std;

/* function to find and print the longest common


subsequence of X[0..m-1] and Y[0..n-1] */
void printLCSubStr(char* X, char* Y, int m, int n)
{
// Create a table to store lengths of longest common
// suffixes of subsequence. Note that LCSuff[i][j]
// contains length of longest common suffix of X[0..i-1]
// and Y[0..j-1]. The first row and first column entries
// have no logical meaning, they are used only for
// simplicity of program
int LCSuff[m + 1][n + 1];

// To store length of the longest common subsequence


int len = 0;

// To store the index of the cell which contains the


// maximum value. This cell's index helps in building
// up the longest common substring from right to left.
int row, col;

/* Following steps build LCSuff[m+1][n+1] in bottom


up fashion. */
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0)
LCSuff[i][j] = 0;

else if (X[i - 1] == Y[j - 1]) {


LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1;
if (len < LCSuff[i][j]) {
len = LCSuff[i][j];
row = i;
col = j;
}
}

47
else
LCSuff[i][j] = 0;
}
}

// if true, then no common subsequence exists


if (len == 0) {
cout << "No Common Subsequence";
return;
}

// allocate space for the longest common subsequence


char* resultStr = (char*)malloc((len + 1) * sizeof(char));

// traverse up diagonally form the (row, col) cell


// until LCSuff[row][col] != 0
while (LCSuff[row][col] != 0) {
resultStr[--len] = X[row - 1]; // or Y[col-1]

// move diagonally up to previous cell


row--;
col--;
}

// required longest common substring


cout << resultStr;
}

/* Driver program to test above function */


int main()
{
char X[] = "OldSite:GeeksforGeeks.org";
char Y[] = "NewSite:GeeksQuiz.com";

int m = strlen(X);
int n = strlen(Y);

printLCSubStr(X, Y, m, n);
return 0;
}

48
Output :

49
Aim of Program : To implement Huffman Coding

#include <bits/stdc++.h>
using namespace std;

// A Huffman tree node


struct MinHeapNode {

// One of the input characters


char data;

// Frequency of the character


unsigned freq;

// Left and right child


MinHeapNode *left, *right;

MinHeapNode(char data, unsigned freq)

left = right = NULL;


this->data = data;
this->freq = freq;
}
};

// For comparison of
// two heap nodes (needed in min heap)
struct compare {

bool operator()(MinHeapNode* l, MinHeapNode* r)

{
return (l->freq > r->freq);
}
};

// Prints huffman codes from


// the root of Huffman Tree.
void printCodes(struct MinHeapNode* root, string str)
{

if (!root)

50
return;

if (root->data != '$')
cout << root->data << ": " << str << "\n";

printCodes(root->left, str + "0");


printCodes(root->right, str + "1");
}

// The main function that builds a Huffman Tree and


// print codes by traversing the built Huffman Tree
void HuffmanCodes(char data[], int freq[], int size)
{
struct MinHeapNode *left, *right, *top;

// Create a min heap & inserts all characters of data[]


priority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> minHeap;

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


minHeap.push(new MinHeapNode(data[i], freq[i]));

// Iterate while size of heap doesn't become 1


while (minHeap.size() != 1) {

// Extract the two minimum


// freq items from min heap
left = minHeap.top();
minHeap.pop();

right = minHeap.top();
minHeap.pop();

// Create a new internal node with


// frequency equal to the sum of the
// two nodes frequencies. Make the
// two extracted node as left and right children
// of this new node. Add this node
// to the min heap '$' is a special value
// for internal nodes, not used
top = new MinHeapNode('$', left->freq + right->freq);

top->left = left;
top->right = right;

minHeap.push(top);
}

51
// Print Huffman codes using
// the Huffman tree built above
printCodes(minHeap.top(), "");
}

// Driver program to test above functions


int main()
{

char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };


int freq[] = { 5, 9, 12, 13, 16, 45 };

int size = sizeof(arr) / sizeof(arr[0]);

HuffmanCodes(arr, freq, size);

return 0;
}

Output:

52

You might also like