ADSA Lab Manual Newnew
ADSA Lab Manual Newnew
ALGORITHMS LABORATORY
I SEMESTER – R 2021
LABO
2
Ex.NO:1:Implementationofrecursivefunctionfortreetraversalan
dFibonacci
1A:TreeTraversalusingRecursive:
Algorithm
AlgorithmInorder(tree)
1. Traversetheleftsubtree,i.e.,callInorder(left-subtree)
2. Visittheroot.
3. Traverse the right subtree, i.e., call Inorder(right-
subtree)AlgorithmPreorder(tree)
1. Visittheroot.
2. Traversetheleftsubtree,i.e.,callPreorder(left-subtree)
3. Traversetherightsubtree,i.e.,callPreorder(right-subtree)
AlgorithmPostorder(tree)
1. Traversetheleftsubtree,i.e.,callPostorder(left-subtree)
2. Traversetherightsubtree,i.e.,callPostorder(right-subtree)
3. Visittheroot.
#include
<iostream>usingnam
espacestd;
/* Abinarytreenodehasdata,pointerto leftchildand
apointertorightchild*/
structNode
{
intdata;
struct Node* left,
*right;Node(intdata)
{
this-
>data=data;left=righ
t=NULL;
}
};
/*Givena binarytree,printitsnodesaccording to
the"bottom-up"postordertraversal.*/
voidprintPostorder(structNode*node)
{
if (node ==
NULL)retu
rn;
->left);
4
//
thenrecuronrightsubtreeprint
Postorder(node->right);
/*Givena
binarytree,printitsnodesininorder*/voidprintInord
er(structNode*node)
{
if (node ==
NULL)retu
rn;
/*firstrecuronleftchild*/
printInorder(node->left);
/*nowrecur
onrightchild*/printInorder(n
ode->right);
}
/*Givenabinarytree,printitsnodesinpreorder*/
voidprintPreorder(structNode*node)
{
if (node ==
NULL)retu
rn;
/*thenrecuronleftsubtree*/
printPreorder(node->left);
/*nowrecuronright
subtree*/printPreorder(node-
>right);
}
root->left->left = new
Node(4);root->left-
>right=newNode(5);
cout<<"\nInordertraversalofbinarytreeis\
n";printInorder(root);
cout <<"\nPostordertraversalofbinarytreeis\
n";printPostorder(root);
return0;
}
Output
Preordertraversalofbinarytreeis1
2453
Inordertraversalofbinary treeis4
2513
Postordertraversalofbinarytreeis4 5
231
Alternate
#include
<iostream>usingnam
espacestd;
//
Datastructuretostoreabinarytreenodestruct
Node
{
intdata;
Node*left,*right;
Node(intdata)
{
this->data=data;
this->left =this->right=nullptr;
}
};
//Recursivefunctionto performpreordertraversalon
thetreevoidpreorder(Node* root)
{
//
ifthecurrentnodeisemptyif(roo
t==nullptr){
return;
}
//
Displaythedatapartoftheroot(orcurrentnode)cout<<
root->data<<"";
7
//
Traversetheleftsubtreepre
order(root->left);
8
// Traversethe right
subtreepreorder(root-
>right);
}
intmain()
{
/*Constructthefollowingtree
1
/\
/ \
2 3
/ / \
/ / \
4 5 6
/\
/\
7 8
*/
preorder(root);
return0;
}
Output
12435786
1B:Fibonacci using
Recursive:Algorithm
1. START
2. Input thenon-negativeinteger‘n’
3. If (n==o ||
n==1)returnn;
9
else
returnfib(n-1)+fib(n-2);
10
4. Print,nthFibonaccinumber
5. END
#include<iostream>u
singnamespacestd;
voidprintFibonacci(intn)
{static int n1=0, n2=1,
n3;if(n>0){
n3 = n1 +
n2;n1 = n2;
n2 =
n3;cout<<n3<<
"";
printFibonacci(n-1);
}
}
int main()
{intn;
cout<<"Enterthenumberofelements:";cin
>>n;
cout<<"FibonacciSeries:";c
out<<"0"<<"1";
printFibonacci(n-2);//n-2because
2numbersarealreadyprintedreturn0;
}
Output
Enter the number of
elements:10FibonacciSeries:01123581
32134
11
IterationAlgorithm
1) CreateanemptystackS.
2) Initializecurrentnodeasroot
3) PushthecurrentnodetoSandsetcurrent=current->leftuntilcurrentisNULL
4) IfcurrentisNULLandstackisnotemptythen
a) Popthetopitemfromstack.
b) Print thepoppeditem,set current=popped_item->right
c) Gotostep3.
5) IfcurrentisNULLandstackisemptythenwearedone.
#include
<iostream>#include
<stack>usingnamesp
acestd;
//
Datastructuretostoreabinarytreenodestruct
Node
{
intdata;
Node*left,*right;
Node(intdata)
{
this->data=data;
this->left =this->right=nullptr;
}
};
//Iterativefunctiontoperformpreordertraversalon
thetreevoidpreorderIterative(Node*root)
{
//returnifthetree
isemptyif(root==nullptr)
return;
//createanempty
stackandpushtherootnodestack<Node*>stack;
stack.push(root);
//pop anodefromthestack
andprintitNode*curr= stack.top();
13
stack.pop();
cout<<curr->data<<"";
//therightchildmustbepushed firstsothattheleftchild
//isprocessedfirst(LIFOorder)
}
}
intmain()
{
/*Constructthefollowingtree
1
/\
/ \
2 3
/ /\
/ / \
4 5 6
/\
/\
7 8
*/
Node*root=newNode(1);ro
ot->left = new
Node(2);root-
>right=newNode(3);
root->left->left=
newNode(4);root->right-
>left=newNode(5);root->right-
>right=newNode(6);
root->right->left->left = new
Node(7);root->right->left->right = new
Node(8);preorderIterative(root);
return0;
}
Output
12435786
14
2B:FibonacciwithIteration
#include
<iostream>usingnam
espacestd;intmain(){
intn1=0,n2=1,n3,i,number;cout<<"Ente
rthenumberofelements:";cin>>number;
cout<<n1<<""<<n2<<" ";//printing0and1
for(i=2;i<number;++i)//loopstartsfrom2because0and1arealreadyprinted
{
n3=n1+n2;cout
<<n3<<"
";n1=n2;
n2=n3;
}
return0;
}
Output
Enterthenumberofelements:90 1
1 2 3 5 8 13 21
15
EX.NO:3:ImplementationofMergeSortandQuickSort
3A.MergeSortAl
gorithm
TheMergeSortfunction repeatedlydividesthearrayinto
twohalvesuntilwereachastagewherewetrytoperformMergeSortonasubarrayofsize1i.e.
p ==r.
After that, the merge function comes into play and combines the sorted arrays
intolargerarraysuntilthewholearrayismerged.
#include<iostream>u
singnamespacestd;
voidswapping(int&a,int&b){ //swap the content of a and
binttemp;
temp=a;a
= b;
b=temp;
}
void display(int *array, int size)
{for(inti=0;i<size;i++)
cout<<array[i]<<"";co
ut<<endl;
}
void merge(int *array, int l, int m, int r)
{inti,j,k,nl,nr;
//size of left and right sub-
arraysnl=m-l+1;nr=r-m;
intlarr[nl],rarr[nr];
//fillleftandrightsub-
arraysfor(i=0;i<nl;i++)
larr[i] =
array[l+i];for(j=0;j<
nr;j++)
rarr[j] =
array[m+1+j];i= 0;j=
0;k =l;
//
margetemparraystorealarraywhil
e(i<nl&&j<nr){
if(larr[i]<=rarr[j])
{array[k] =
larr[i];i++;
}else{
array[k] =
rarr[j];j++;
}
k++;
16
}
while(i<nl){ //extra element in left
arrayarray[k]=larr[i];
17
i++;k++;
}
while(j<nr){
//extraelementinrightarrayarray[k]=rarr[j];
j++;k++;
}
}
voidmergeSort(int*array,intl,intr)
{intm;
if(l<r){
int m=l+(r-l)/2;
//
Sortfirstandsecondarraysmer
geSort(array,l,
m);mergeSort(array,m+1,
r);merge(array,l,m,r);
}
}
int main()
{intn;
cout<<"Enterthenumberofelements:";cin>
>n;
intarr[n];
//createanarraywithgivennumberofelementscout<<"Enterele
ments:"<<endl;
for(int i = 0; i<n; i++)
{cin>>arr[i];
}
cout<<"ArraybeforeSorting:";dis
play(arr,n);
mergeSort(arr,0,n-1); //(n-
1)forlastindexcout<<"Array afterSorting:";
display(arr,n);
}
Output
Enterthenumberofelements:5En
terelements:
94178
ArraybeforeSorting:94178
Array afterSorting:1 4 7 8 9
3B.QuickSortAlg
orithm
fromthearray).
19
While dividing the array, the pivot element should be positioned in such a way
thatelements less than pivot are kept on the left side and elements greater than pivot
areon therightsideofthepivot.
2. Theleftandrightsubarraysarealsodividedusingthesameapproach.Thisprocesscontinu
esuntileachsubarraycontainsasingleelement.
3. At this point, elements are already sorted. Finally, elements are combined to form
asortedarray.
#include
<iostream>usingnam
espacestd;
void
quick_sort(int[],int,int);intpa
rtition(int[],int,int);
intmain()
{
inta[50],n,i;
cout<<"Howmanyelements?";c
in>>n;
cout<<"\nEnterarrayelements:";
for(i=0;i<n;i+
+)cin>>a[i];
quick_sort(a,0,n-1);cout<<"\
nArrayaftersorting:";
for(i=0;i<n;i+
+)cout<<a[i]<<"
";
return0;
}
voidquick_sort(inta[],intl,intu)
{
intj;if(
l<u)
{
j=partition(a,l,u);q
uick_sort(a,l,j-
1);quick_sort(a,j+1,
u);
}
}
intpartition(inta[],intl,intu)
{
int
v,i,j,temp;v=
a[l];
i=l;j=u
20
+1;
do
{
21
do
i++;
while(a[i]<v&&i<=u);
do
j--;
while(v<a[j]);
if(i<j)
{
temp=a[i];
a[i]=a[j];a
[j]=temp;
}
}while(i<j);
a[l]=a[j];
a[j]=v;
return(j);
}
Output
Howmanyelements?7
Enterarrayelements:3719542
Arrayaftersorting:1234579
22
EX.NO:4:ImplementationofaBinarySearchTree
Algorithm
Abinarysearchtreefollowssomeordertoarrangetheelements.InaBinarysearchtree,thevalu
eofleftnodemustbesmallerthantheparentnode, andthevalueofrightnodemustbe
greaterthantheparentnode.Thisruleisappliedrecursivelytotheleftandright subtreesoftheroot.
SearchinBST
Ifroot==NULLreturn
NULL;
Ifnumber==root-
>datareturnroot->data;
Ifnumber<root-
>datareturnsearch(root-
>left)
Ifnumber>root-
>datareturnsearch(root-
>right)
Insert
Ifnode==NULL
returncreateNode(data)i
f(data<node->data)
node->left=insert(node-
>left,data);elseif(data>node->data)
node->right=insert(node-
>right,data);return node;
Remove
Therearethreecasesfordeletinga nodefromabinarysearchtree.
CaseI
In the first case, the node to be deleted is the leaf node. In such a case, simply delete the
nodefromthetree.
CaseII
In the second case, the node to be deleted lies has a single child node. In such a case
followthestepsbelow:
1. Replacethatnodewithitschildnode.
2. Removethe childnodefromitsoriginalposition.
CaseIII
In the third case, the node to be deleted has two children. In such a case follow the
stepsbelow:
Gettheinordersuccessorofthatnode.Replacet
henodewiththeinordersuccessor.
Removetheinordersuccessorfromitsoriginalposition.
#include<iostream>u
singnamespacestd;
class BST
{structnode{
23
intdata;nod
e*
left;node*ri
ght;
};
node*root;
node* makeEmpty(node* t)
{if(t== NULL)
returnNULL;
{
makeEmpty(t-
>left);makeEmpty(t-
>right);deletet;
}
returnNULL;
}
node*insert(intx,node*t)
{
if(t==NULL)
{
t = new
node;t-
>data=x;
t->left=t->right=NULL;
}
elseif(x<t->data)
t->left = insert(x, t-
>left);elseif(x >t->data)
t->right=insert(x,t-
>right);return t;
}
node*findMin(node*t)
{
if(t==NULL)
returnNULL;
elseif(t->left==
NULL)return t;
else
returnfindMin(t->left);
}
node*findMax(node*t)
{if(t== NULL)
returnNULL;
elseif(t-
>right==NULL)return
t;
else
24
returnfindMax(t->right);
25
return t;
}
void inorder(node* t)
{if(t== NULL)
return;inorde
r(t->left);
cout<<t-
>data<<"";inorder(t-
>right);
}
public:
BST(){
27
root=NULL;
}
~BST(){
root =makeEmpty(root);
}
voidinsert(intx){
root=insert(x,root);
}
voidremove(intx){
root =remove(x,root);
}
void display()
{inorder(root
);cout<<endl
;
}
void search(intx)
{root=find(root,x);
}
};
int main()
{BSTt;
t.insert(20);
t.insert(25);
t.insert(15);
t.insert(10);
t.insert(30);
t.display();
t.remove(20);
t.display();
t.remove(25);
t.display();
t.remove(30);
t.display();
return0;
}
Output
10 15 25 30 70
10 15 25 30 70
10 15 30 70
10 15 70
28
EX.NO:5:Red-BlackTreeImplementation
Red-Black tree is a self-balancingbinary search tree in which each node contains an extra
bitfordenotingthecolorofthenode,eitherred orblack.
Ared-blacktreesatisfiesthefollowing properties:
1. Red/BlackProperty:Everynodeiscolored, eitherredorblack.
2. RootProperty:Therootisblack.
3. LeafProperty:Everyleaf(NIL)isblack.
4. Red Property:Ifarednodehaschildren then, thechildren arealwaysblack.
5. Depth Property: For each node, any simple path from this node to any of
itsdescendantleafhasthesameblack-depth(thenumberofblacknodes).
AlgorithmL
eftRotate
In left-rotation, the arrangement of the nodes on the right is transformed into
thearrangementsontheleftnode.
Algorithm
1. Lettheinitialtreebe: Initialtree
2. Ifyhasaleftsubtree,assignxastheparentoftheleftsubtreeofy.
Assignxastheparentoftheleftsubtreeofy
3. IftheparentofxisNULL,makeyastherootofthetree.
4. Elseifxistheleftchildofp,makeyastheleftchildofp.
6. Makeyastheparentofx. Assignyastheparentofx.
RightRotate
In right-rotation, the arrangement of the nodes on the left is transformed into
thearrangementsontherightnode.
1. Lettheinitialtreebe: InitialTree
2. Ifxhasarightsubtree,assignyastheparentoftherightsubtreeofx.
Assignyastheparentoftherightsubtreeofx
3. IftheparentofyisNULL,makexastherootofthetree.
4. Else ifyisthe rightchildofitsparentp,makexastherightchildof p.
5. Elseassignxastheleftchildofp. Assigntheparentofyasthepare
ntofx
6. Makexastheparentofy. Assignxastheparentofy
30
Left-RightandRight-LeftRotate
Inleft-rightrotation,thearrangementsarefirstshiftedtotheleftandthentotheright.
1. Do left rotation on x-
y.Leftrotatex-y
2. Dorightrotationony-
z.Rightrotatez-y
Inright-leftrotation,thearrangementsarefirstshiftedtotherightandthentotheleft.
1. Dorightrotationonx-y.
Rightrotatex-y
31
2. Do left rotation on z-
y.Leftrotatez-y
Algorithmtoinsertanode
Followingstepsarefollowedforinsertinganewelementintoared-blacktree:
1. Lety betheleaf(ie.NIL)andxbetherootofthetree.
2. Check if the tree is empty (ie. whether x is NIL). If yes, insert newNode as a
rootnodeandcoloritblack.
3. Else,repeatstepsfollowingstepsuntilleaf(NIL)isreached.
. ComparenewKeywithrootKey.
a. IfnewKeyisgreaterthan rootKey,traversethrough therightsubtree.
b. Elsetraversethroughtheleftsubtree.
4. AssigntheparentoftheleafasaparentofnewNode.
5. IfleafKeyisgreaterthannewKey,makenewNodeasrightChild.
6. Else,makenewNodeas leftChild.
7. AssignNULLtotheleftandrightChildofnewNode.
8. AssignREDcolortonewNode.
9. CallInsertFix-algorithmtomaintainthepropertyofred-black treeifviolated.
Whynewlyinsertednodesarealwaysredinared-blacktree?
This is because inserting a red node does not violate the depth property of a red -black
tree.If you attach a red node to a red node, then the rule is violated but it is easier to fix
thisproblemthan theproblemintroducedbyviolatingthedepthproperty.
Algorithmtomaintainred-blackpropertyafterinsertion
Thisalgorithmisusedformaintainingthepropertyofared-
blacktreeiftheinsertionofanewNodeviolatesthisproperty.
1. DothefollowingwhiletheparentofnewNodepisRED.
2. Ifp istheleftchildofgrandParentgPofz, dothefollowing.
Case-I:
. IfthecoloroftherightchildofgPofzisRED,setthecolorofboth thechildren
ofgPasBLACKandthecolorofgPasRED.
a. AssigngPtonewNode.
Case-II:
b. ElseifnewNodeistherightchildofp then,assignp to newNode.
c. Left-RotatenewNode.
Case-III:
d. Setcolorofp asBLACKandcolorofgPasRED.
e. Right-RotategP.
32
3. Else,dothefollowing.
. IfthecoloroftheleftchildofgPofzisRED,setthecolorofboththechildren
ofgPasBLACKand thecolorofgPasRED.
a. AssigngPtonewNode.
b. ElseifnewNodeisthe leftchildofpthen,assignptonewNodeandRight-
RotatenewNode.
c. Setcolorofp asBLACKandcolorofgPasRED.
d. Left-RotategP.
4. Settherootofthetreeas BLACK.
Algorithmtodeleteanode
1. SavethecolorofnodeToBeDeletedinorigrinalColor.
2. Iftheleftchildof nodeToBeDeletedisNULL
. AssigntherightchildofnodeToBeDeletedtox.
a. TransplantnodeToBeDeletedwithx.
3. ElseiftherightchildofnodeToBeDeleted isNULL
. Assignthe leftchildofnodeToBeDeletedintox.
a. TransplantnodeToBeDeletedwithx.
4. Else
. AssigntheminimumofrightsubtreeofnoteToBeDeleted intoy.
a. SavethecolorofyinoriginalColor.
b. AssigntherightChildofyintox.
c. Ify isachildofnodeToBeDeleted,thensettheparentofx asy.
d. Else,transplantywithrightChildofy.
e. TransplantnodeToBeDeletedwithy.
f. SetthecolorofywithoriginalColor.
5. IftheoriginalColorisBLACK,callDeleteFix(x).
AlgorithmtomaintainRed-Blackpropertyafterdeletion
Thisalgorithmisimplementedwhenablacknodeisdeleted
becauseitviolatestheblackdepthproperty ofthered-black tree.
Thisviolationiscorrectedbyassumingthatnodex(whichisoccupyingy'soriginalposition)
has an extra black. This makes node x neither red nor black. It is either
doublyblackorblack-and-red.Thisviolatesthered-blackproperties.
However, the color attribute of x is not changed rather the extra black is represented
inx'spointingto thenode.
Theextrablackcanberemovedif
1. Itreachestherootnode.
2. Ifxpointstoared-blacknode.Inthiscase,x iscoloredblack.
3. Suitablerotationsandrecoloringareperformed.
Thefollowingalgorithmretainsthepropertiesofared-blacktree.
1. DothefollowinguntilthexisnottherootofthetreeandthecolorofxisBLACK
2. Ifxistheleftchildofitsparentthen,
. Assignwtothesiblingofx.
a. Iftherightchildofparentofx isRED,
Case-I:
. Setthecoloroftherightchildoftheparentofx asBLACK.
a. SetthecoloroftheparentofxasRED.
b. Left-Rotatetheparentofx.
c. Assign the rightChildoftheparentofx to w.
33
b. IfthecolorofboththerightandtheleftChildofwisBLACK,
Case-II:
. SetthecolorofwasRED
a. Assigntheparentofxto x.
c. ElseifthecoloroftherightChildofwisBLACK
Case-III:
. Setthe coloroftheleftChildofwasBLACK
a. SetthecolorofwasRED
b. Right-Rotatew.
c. Assign the rightChildoftheparentofx to w.
d. Ifanyofthe above casesdonotoccur,thendothefollowing.
Case-IV:
. Setthecolorofwasthecoloroftheparentofx.
a. Setthe coloroftheparentofxasBLACK.
b. SetthecoloroftherightchildofwasBLACK.
c. Left-Rotatetheparent ofx.
d. Setxastherootofthetree.
3. Elsethesameasabovewithrightchangedtoleftandviceversa.
4. Setthe colorofxasBLACK.
#include
<cstdlib>#include<st
dexcept>#include
<iostream>usingnam
espacestd;
template<typenameKey,typenameValue>cl
assRedBlack
{
public:RedB
lack()
:root(NULL)
{
}
~RedBlack()
{
DeleteNode(root);
}
voidInsert(constKey&key,constValue&value)
{
Node*node,*parent,*z;
parent=NULL;n
ode =
root;while(node
)
{
34
parent=node;
35
if(key<node->key)
{
node=node->left;
}
else
{
node=node->right;
}
}
if(!parent)
{
z=root=newNode;z-
>key=key;
z->value=value;
z->colour=BLACK;
z->parent=z->left=z->right=NULL;
}
else
{
z=newNode;z-
>key=key;
z->value =
value;z->colour
=RED;
z->parent=parent;
z->left=z->right=NULL;
if(z->key<parent->key)
{
parent->left=z;
}
else
{
parent->right=z;
}
}
Node
*uncle;boolsi
de;
while(z->parent&&z->parent->colour==RED)
{
if((side=(z->parent==z->parent->parent->left)))
{
uncle=z->parent->parent->right;
}
else
{
uncle=z->parent->parent->left;
}
36
if(uncle&&uncle->colour==RED)
{
z->parent-
>colour=BLACK;uncle-
>colour= BLACK;
z->parent->parent-
>colour=RED;z=z->parent-
>parent;
}
else
{
if(z==(side?z->parent->right:z->parent->left))
{
z=z->parent;
side?RotateLeft(z): RotateRight(z);
}
z->parent->colour= BLACK;
z->parent->parent->colour=RED;
side?RotateRight(z->parent->parent):RotateLeft(z->parent->parent);
}
}
root->colour=BLACK;
}
Value&Find(constKey&key)
{
Node *node =
root;while(node)
{
if(node->key<key)
{
node=node->left;
}
elseif(node->key>key)
{
node=node->right;
}
else
{
returnnode->value;
}
}
throwstd::runtime_error("Keynotfound");
}
voidDelete(constKey&key)
{
Node *node =
root;while(node)
37
{
if(node->key>key)
{
node=node->left;
}
elseif(node->key<key)
{
node=node->right;
}
else
{
break;
}
}
if(!node||node->key!=key)
{
return;
}
Colour
original;Node
*sub, *old;if(!
node->left)
{
Transplant(node,sub=node->right);
}
elseif (!node->right)
{
Transplant(node,sub=node->left);
}
else
{
old=Minimum(node-
>right);original=old->colour;
sub=old->right;
if(old->parent==node)
{
sub->parent=node;
}
else
{
Transplant(old,old-
>right);old->right=node-
>right;old->right-
>parent=old;
}
Transplant(node,
old);old->left = node-
>left;old->left-
38
>parent= old;
39
old->colour=node->colour;
}
deletenode;
if(original==BLACK)
{
bool
side;Node*sib
ling;
while(old!=root&&old->colour==BLACK)
{
if((side=(old==old->parent->left)))
{
sibling=old->parent->right;
}
else
{
sibling=old->parent->left;
}
if(sibling->colour==RED)
{
sibling->colour=
BLACK;old->parent-
>colour=RED;
side ? RotateLeft(old->parent) : RotateRight(old-
>parent);sibling=side?old->parent->right:old->parent->left;
}
if(sibling->left->colour==BLACK&&sibling->right->colour==RED)
{
sibling-
>colour=RED;old=old-
>parent;
}
else
{
if(BLACK==side?sibling->right->colour:sibling->left->colour)
{
sibling-
>colour=RED;if(side)
{
sibling->left-
>colour=BLACK;RotateRight(si
bling);
sibling=old->parent->right;
}
else
{
sibling->right-
>colour=BLACK;RotateLeft(sibli
ng);
40
sibling=old->parent->left;
}
}
41
sibling->colour=old->parent-
>colour;old->parent-
>colour=BLACK;
if(side)
{
sibling->left-
>colour=BLACK;RotateLeft(old
->parent);
}
else
{
sibling->right-
>colour=BLACK;RotateRight(ol
d->parent);
}
old=root;
}
}
}
}
voidDump()
{
Dump(root,0);
}
private:
enumColour
{
RED,BLAC
K
};
structNode
{
Colour
colour;Key
key;Value
value;Node
*parent;Node
*left;Node*ri
ght;
};
Node*root;
voidRotateLeft(Node*x)
{
Node*y;
42
y=x->right;
x->right=y->left;
43
if(y->left)
{
y->left->parent=x;
}
y->parent=x-
>parent;y->left= x;
if(!x->parent)
{
root=y;
}
elseif(x==x->parent->left)
{
x->parent->left=y;
}
else
{
x->parent->right=y;
}
x->parent=y;
}
voidRotateRight(Node*y)
{
Node*x;
x =y->left;
y->left=x-
>right;if(x->right)
{
x->right->parent=y;
}
x->parent=y-
>parent;x->right=y;
if(!y->parent)
{
root=x;
}
elseif(y==y->parent->left)
{
y->parent->left=x;
}
else
{
y->parent->right=x;
}
44
y->parent=x;
}
void Transplant(Node*dest,Node*src)
{
if(dest->parent== NULL)
{
root=src;
}
elseif(dest==dest->parent->left)
{
dest->parent->left=src;
}
else
{
dest->parent->right=src;
}
if(src)
{
src->parent=dest->parent;
}
}
Node*Minimum(Node*tree)
{
while(tree->left)
{
tree= tree->left;
}
returntree;
}
voidDump(Node*node,inttabs)
{
if(!node)
{
return;
}
Dump(node->left,tabs+1);
for(inti=0;i<tabs;++i)
{
std::cout<<"\t\t";
}
std::cout<<node->key <<(node-
>colour?"B":"R")<<std::endl;Dump(node->right,tabs+ 1);
45
voidDeleteNode(Node*node)
{
if(!node)
{
return;
}
if(node->left)
{
DeleteNode(node->left);
}
if(node->right)
{
DeleteNode(node->right);
}
deletenode;
}
};
intmain()
{
RedBlack<int, int>
tree;for(inti=1;i<10;++i)
{
tree.Insert(i,i);
}
tree.Delete(9);
tree.Delete(8);
tree.Dump();r
eturn0;
}
Output
1B
2R
3B
4B
5B
6R
7R
46
EX.NO:6:HeapImplementation
Max-heap Min-heap
heap.Heap Operations
Some of the importantoperations performed on a heap are described below along with
theiralgorithms.
Heapify
Heapify is the process of creating a heap data structure from a binary tree. It is used to
createaMin-HeaporaMax-Heap.
1. Lettheinputarraybe
InitialArray
2. Createacompletebinarytreefromthearray
Completebinarytree
47
3. Startfromthefirstindexofnon-leafnodewhoseindexisgivenbyn/2 -1.
Startfromthefirstonleafnode
4. Setcurrentelementiaslargest.
5. Theindexofleftchildisgivenby2i+1and
therightchildisgivenby2i+2.IfleftChildisgreaterthancurrentElement(i.e.element
atithindex),
setleftChildIndexaslargest.
IfrightChildisgreaterthanelementinlargest,setrightChildIndexaslargest.
6. SwaplargestwithcurrentElement Swapifnecessary
7. Repeatsteps3-7untilthesubtreesarealsoheapified.
AlgorithmHeapify(ar
ray,size,i)setiaslarges
tleftChild = 2i +
1rightChild=2i+2
if leftChild >
array[largest]set
leftChildIndex as
largestifrightChild
>array[largest]
setrightChildIndexaslargest
swaparray[i]andarray[largest]
TocreateaMax-Heap:
MaxHeap(array,size)
loopfromthefirstindexofnon-
leafnodedowntozerocallheapify
ForMin-Heap,bothleftChildandrightChildmustbelargerthantheparentforallnodes.
InsertElementintoHeap
AlgorithmforinsertioninMaxHeap
Ifthereisnonode,
48
createanewNode.
else(a nodeisalreadypresent)
insertthenewNodeatthe end(lastnodefromlefttoright.)
heapifythearray
1. Insertthenewelementattheendofthetree.Inse
rtattheend
2. Heapifythe tree.
Heapifythearray
ForMinHeap,theabovealgorithmismodifiedsothatparentNodeisalwayssmallerthannewN
ode.
DeleteElementfromHeapAlgorith
mfordeletioninMaxHeapIfnodeToB
eDeletedistheleafNoderemovetheno
de
ElseswapnodeToBeDeletedwiththelastLeafNoderemo
venoteToBeDeleted
heapifythearray
1. Selecttheelementtobedeleted.Se
lecttheelementtobedeleted
49
3. Removethelastelement. Removethelastele
ment
4. Heapifythetree.
Heapifythearray
ForMinHeap,abovealgorithmismodifiedsothatbothchildNodesaregreatersmallerthancurr
entNode.
Peek(Findmax/min)
Peekoperationreturnsthe maximumelementfromMaxHeaporminimumelementfromMinHeap
withoutdeletingthenode.
For both Max heap and Min
Heapreturn rootNode
Extract-Max/Min
Extract-MaxreturnsthenodewithmaximumvalueafterremovingitfromaMax
HeapwhereasExtract-MinreturnsthenodewithminimumafterremovingitfromMinHeap
50
/*C++ProgramtoImplementHeap
*/
#include<iostream>
#include<cstdlib>#in
clude<vector>#includ
e<iterator>usingname
spacestd;
/*
*ClassDeclaration
*/
classHeap
{
private:
vector<int>heap;intl
eft(intparent);intrigh
t(intparent);intparent
(intchild);
voidheapifyup(int
index);voidheapifydown(intin
dex);
public:
Heap()
{}
voidInsert(intelement);vo
idDeleteMin();
intExtract
Min();voidDisplayHe
ap();intSize();
};
/*
*ReturnHeapSize
*/
intHeap::Size()
{
returnheap.size();
}
/*
*InsertElementintoaHeap
*/
voidHeap::Insert(intelement)
{
heap.push_back(element);heapifyup(heap
.size()-1);
}
/*
*DeleteMinimumElement
*/
voidHeap::DeleteMin()
{
if(heap.size()==0)
51
{
cout<<"HeapisEmpty"<<endl;re
turn;
}
heap[0]=heap.at(heap.size()-
1);heap.pop_back();
heapifydown(0);
cout<<"ElementDeleted"<<endl;
}
/*
*ExtractMinimumElement
*/
intHeap::ExtractMin()
{
if(heap.size()==0)
{
return-1;
}
else
returnheap.front();
}
/*
*DisplayHeap
*/
voidHeap::DisplayHeap()
{
vector<int>::iteratorpos=heap.begin();cou
t<<"Heap-->";
while(pos!=heap.end())
{
cout<<*pos<<"";
pos++;
}
cout<<endl;
}
/*
*ReturnLeftChild
*/
intHeap::left(intparent)
{
intl=2*parent+1;if(l<he
ap.size())
returnl;
else
return-1;
}
52
/*
*ReturnRightChild
*/
intHeap::right(intparent)
{
intr=2*parent+2;if(r<he
ap.size())
returnr;el
se
return-1;
}
/*
*ReturnParent
*/
intHeap::parent(intchild)
{
intp=(child-1)/
2;if(child==0)
return-
1;else
returnp;
}
/*
*Heapify-MaintainHeapStructurebottomup
*/
voidHeap::heapifyup(intin)
{
if(in>=0&&parent(in)>=0&&heap[parent(in)]>heap[in])
{
inttemp
=heap[in];heap[in]=heap[par
ent(in)];heap[parent(in)]=te
mp; heapifyup(parent(in));
}
}
/*
*Heapify-MaintainHeapStructuretopdown
*/
voidHeap::heapifydown(intin)
{
intchild=
left(in);intchild1=right
(in);
if(child >=0&&child1>=0&&heap[child]>heap[child1])
{
child=child1;
}
53
if(child>0)
{
inttemp
=heap[in];heap[in]=hea
p[child];heap[child]
=temp;heapifydown(ch
ild);
}
}
/*
*MainContainsMenu
*/
intmain()
{
Heaph;whil
e(1)
{
cout<<"--------------------"<<endl;
cout<<"OperationsonHeap"<<endl;c
out<<"----------------------"<<endl;
cout<<"1.InsertElement"<<endl;
cout<<"2.Delete
MinimumElement"<<endl;cout<<"3.Extract
MinimumElement"<<endl;cout<<"4.PrintHeap"<<endl;
cout<<"5.Exit"<<endl;
intchoice,element;
cout<<"Enter your
choice:";cin>>choice;
switch(choice)
{
case1:
cout<<"Entertheelementtobeinserted:";cin>>element;
h.Insert(element);br
eak;
case2:
h.DeleteMin();
break;
case3:
cout<<"MinimumElement:";if(
h.ExtractMin()==-1)
{
cout<<"HeapisEmpty"<<endl;
}
else
cout<<"MinimumElement:"<<h.ExtractMin()<<endl;break;
case4:
cout<<"DisplayingelementsofHwap:";
h.DisplayHeap();
54
break;
case5:
exit(1);
default:
cout<<"EnterCorrectChoice"<<endl;
}
}
return0;
}
Output
OperationsonHeap
1. InsertElement
2. Delete Minimum
Element3.Extract Minimum
Element4.PrintHeap
5.Exit
Enteryourchoice:1
Entertheelementtobeinserted:1
OperationsonHeap
1. InsertElement
2. Delete Minimum
Element3.Extract Minimum
Element4.PrintHeap
5.Exit
Enteryourchoice:1
Entertheelementtobeinserted:2
OperationsonHeap
1. InsertElement
2. Delete Minimum
Element3.Extract Minimum
Element4.PrintHeap
5.Exit
Enteryourchoice:1
Entertheelementtobeinserted:3
OperationsonHeap
1. InsertElement
2. Delete Minimum
Element3.Extract Minimum
Element4.PrintHeap
55
5.Exit
Enteryourchoice:1
Entertheelementtobeinserted:4
OperationsonHeap
1. InsertElement
2. Delete Minimum
Element3.Extract Minimum
Element4.PrintHeap
5.Exit
Enteryourchoice:1
Entertheelementtobeinserted:5
OperationsonHeap
1. InsertElement
2. Delete Minimum
Element3.Extract Minimum
Element4.PrintHeap
5.Exit
Enteryourchoice:1
Entertheelementtobeinserted:9
OperationsonHeap
1. InsertElement
2. Delete Minimum
Element3.Extract Minimum
Element4.PrintHeap
5.Exit
Enteryourchoice:4
DisplayingelementsofHwap:Heap-->123459
OperationsonHeap
1. InsertElement
2. Delete Minimum
Element3.Extract Minimum
Element4.PrintHeap
5.Exit
Enteryourchoice:1
Entertheelementtobeinserted:7
OperationsonHeap
1. InsertElement
2. Delete Minimum
Element3.Extract Minimum
Element4.PrintHeap
56
5.Exit
Enter your choice:
4DisplayingelementsofHwap: Heap--> 1 2 3 4 5 9 7
Operationson Heap
1.InsertElement
2.Delete Minimum
Element3.ExtractMinimum
Element
4.Print
Heap5.Exit
Enteryourchoice:2
ElementDeleted
Operationson Heap
1.InsertElement
2.Delete Minimum
Element3.ExtractMinimum
Element
4.Print
Heap5.Exit
Enteryourchoice:4
DisplayingelementsofHwap: Heap--> 2 4 3 7 5 9
Operationson Heap
1. InsertElement
2. Delete Minimum
Element3.Extract Minimum
Element4.PrintHeap
5.Exit
Enteryourchoice:3
MinimumElement:MinimumElement:2
OperationsonHeap
1. InsertElement
2. Delete Minimum
Element3.Extract Minimum
Element4.PrintHeap
5. Exit
Enteryourchoice:
57
EX.NO:7:FibonacciHeapImplementation
PropertiesofaFibonacciHeap
ImportantpropertiesofaFibonacciheapare:
1. It is a set of min heap-orderedtrees. (i.e. The parent is always smaller than
thechildren.)
2. A pointerismaintainedattheminimumelementnode.
3. Itconsistsofasetofmarkednodes.(Decreasekeyoperation)
4. ThetreeswithinaFibonacciheapareunorderedbutrooted.
Create anewnodefortheelement.
Checkiftheheap isempty.
Iftheheapisempty,setthenewnodeasarootnodeand markitmin.
Else,insertthe nodeinto therootlistand updatemin.
Insertionoperationinfibonacciheap
InsertionExample
insert(H,
x)degree[x]=
0p[x]=NIL
child[x]=NILleft
[x] =
xright[x]=x
mark[x]=FALSE
concatenatetherootlistcontainingxwith
rootlistHifmin[H]==NILorkey[x]<key[min[H]]
then min[H] =
xn[H]= n[H]+1
58
Followingfunctionsareusedfordecreasing thekey.
Decrease-Key
1. Selectthenodetobedecreased,x,andchangeitsvaluetothenewvaluek.
2. If the parent of x, y, is not null and the key of parent is greater than that of the k
thencallCut(x)and Cascading-Cut(y)subsequently.
3. Ifthekeyofxissmallerthanthekeyofmin,thenmarkxasmin.
Cut
1. Remove xfromthe currentpositionand additto therootlist.
2. Ifxismarked,thenmarkitasfalse.
Cascading-Cut
1. Iftheparentofy isnotnullthenfollowthefollowingsteps.
2. Ifyisunmarked,thenmarky.
3. Else,callCut(y)andCascading-Cut(parentofy).
/*
*C++ProgramtoImplementFibonacciHeap
*/
#include
<iostream>#include
<cmath>#include
<cstdlib>usingnames
pacestd;
/*
*NodeDeclaration
*/
structnode
{
intn;
intdegree;nod
e*
parent;node*
child;node*
left;node*
right;charmar
k;charC;
};
/*
59
*ClassDeclaration
*/
classFibonacciHeap
{
private:
intnH;node
*H;
public:
node*InitializeHeap();
intFibonnaci_link(node*,node*,node*);n
ode*Create_node(int);
node *Insert(node *, node
*);node*Union(node*,node*)
;node *Extract_Min(node
*);intConsolidate(node*);
intDisplay(node*);node
*Find(node*,int);
intDecrease_key(node*,int,int);in
tDelete_key(node*,int);
int Cut(node *, node *, node
*);intCascase_cut(node*,node*);
FibonacciHeap()
{
H=InitializeHeap();
}
};
/*
*InitializeHeap
*/
node*FibonacciHeap::InitializeHeap()
{
node*np;np
=NULL;
returnnp;
}
/*
*CreateNode
*/
node*FibonacciHeap::Create_node(intvalue)
{
node* x = new
node;x->n=value;
returnx;
}
/*
*InsertNode
*/
node*FibonacciHeap::Insert(node*H,node*x)
{
x->degree= 0;
60
x->parent =
NULL;x-
>child=NULL;x-
>left= x;
x->right=x;x-
>mark='F';
x->C='N';
if(H!=NULL)
{
(H->left)->right =
x;x->right=H;
x->left = H-
>left;H->left=x;
if (x->n < H-
>n)H= x;
}
else
{
H= x;
}
nH= nH+ 1;
returnH;
}
/*
*LinkNodesinFibonnaciHeap
*/
intFibonacciHeap::Fibonnaci_link(node*H1, node*y, node*z)
{
(y->left)->right=y->right;
(y->right)->left=y-
>left;if(z->right==z)
H1=z;
y->left=y;y-
>right=y;
y->parent=z;
if (z-
>child==NULL)z-
>child=y;
y->right=z->child;
y->left=(z->child)->left;((z-
>child)->left)->right=y;(z-
>child)->left=y;
if(y->n< (z->child)-
>n)z->child=y;
z->degree++;
}
/*
* Union NodesinFibonnaciHeap
*/
node*FibonacciHeap::Union(node*H1,node*H2)
{
node*np;
61
node*H=InitializeHeap();H
= H1;
(H->left)->right = H2;
(H2->left)->right =
H;np =H->left;
H->left = H2-
>left;H2->left =
np;return H;
}
/*
*DisplayFibonnaciHeap
*/
intFibonacciHeap::Display(node*H)
{
node*p=H;
if(p== NULL)
{
cout<<"The Heap is
Empty"<<endl;return0;
}
cout<<"TherootnodesofHeapare:"<<endl;do
{
cout<<p-
>n;p=p-
>right;if(p!
=H)
{
cout<<"-->";
}
}
while(p!=H&&p->right!
=NULL);cout<<endl;
}
/*
* ExtractMinNodein FibonnaciHeap
*/
node*FibonacciHeap::Extract_Min(node*H1)
{
node*
p;node*
ptr;node* z =
H1;p= z;
ptr=z;
if(z== NULL)
return
z;node*
x;node*np;
x =NULL;
if(z->child!
=NULL)x=z-
>child;
62
if(x != NULL)
{
ptr =
x;do
{
np=x->right;
(H1->left)->right =
x;x->right=H1;
x->left=H1-
>left;H1->left=x;
if (x->n < H1-
>n)H1 = x;
x->parent =
NULL;x = np;
}
while(np!=ptr);
}
(z->left)->right=z->right;
(z->right)->left=z-
>left;H1= z->right;
if(z==z->right&&z->child==NULL)H=
NULL;
else
{
H1 = z-
>right;Consolida
te(H1);
}
nH= nH-1;
returnp;
}
/*
*ConsolidateNodeinFibonnaciHeap
*/
intFibonacciHeap::Consolidate(node*H1)
{
intd,i;
floatf=(log(nH))/
(log(2));intD=f;
node*A[D];
for(i=0;i<=D;i+
+)A[i]=NULL;
node* x =
H1;node*
y;node*
np;node* pt =
x;do
{
pt = pt-
>right;d=x-
>degree;
while(A[d]!=NULL)
63
{
y=A[d];
if(x->n>y->n)
{
np =
x;x=y;
y=np;
}
if (y ==
H1)H1=x
;
Fibonnaci_link(H1,y,x);i
f(x->right==x)
H1=x;
A[d]=NULL;
d= d+ 1;
}
A[d]=x;
x=x->right;
}
while(x!
=H1);H=NULL
;
for(intj=0;j<=D;j++)
{
if(A[j]!=NULL)
{
A[j]->left=A[j];
A[j]-
>right=A[j];if(H!
= NULL)
{
(H->left)-
>right=A[j];A[j]-
>right=H;
A[j]->left = H-
>left;H->left=A[j];
if (A[j]->n < H-
>n)H=A[j];
}
else
{
H=A[j];
}
if(H==NULL)H
=A[j];
else if (A[j]->n < H-
>n)H=A[j];
}
}
}
64
/*
*Decreasekey ofNodesin FibonnaciHeap
65
*/
intFibonacciHeap::Decrease_key(node*H1,intx,intk)
{
node*y;
if(H1==NULL)
{
cout<<"The Heap is
Empty"<<endl;return0;
}
node*ptr=Find(H1,x);if(
ptr== NULL)
{
cout<<"Node not found in the
Heap"<<endl;return1;
}
if(ptr->n<k)
{
cout<<"Enteredkeygreaterthancurrentkey"<<endl;ret
urn0;
}
ptr->n=k;
y=ptr->parent;
if(y!=NULL&&ptr->n<y->n)
{
Cut(H1, ptr,
y);Cascase_cut(H1,
y);
}
if (ptr->n < H-
>n)H= ptr;
return0;
}
/*
*CutNodesinFibonnaciHeap
*/
intFibonacciHeap::Cut(node*H1,node*x,node*y)
{
if(x==x->right)
y->child=NULL;
(x->left)->right=x->right;
(x->right)->left=x-
>left;if(x==y->child)
y->child=x->right;
y->degree=y->degree-1;x-
>right=x;
x->left=x;
(H1->left)-
>right=x;x-
>right=H1;
x->left=H1-
>left;H1->left= x;
x->parent=NULL;
66
x->mark='F';
}
/*
* CascadeCuttinginFibonnaciHeap
*/
intFibonacciHeap::Cascase_cut(node*H1,node*y)
{
node* z = y-
>parent;if(z!
=NULL)
{
if(y->mark=='F')
{
y->mark='T';
}
else
{
Cut(H1, y,
z);Cascase_cut(H1,
z);
}
}
}
/*
*Find NodesinFibonnaciHeap
*/
node*FibonacciHeap::Find(node*H,intk)
{
node* x =
H;x->C='Y';
node* p =
NULL;if(x-
>n==k)
{
p = x;
x->C='N';
returnp;
}
if(p== NULL)
{
if(x->child!
=NULL)p=Find(x-
>child,k);
if((x->right)->C!
='Y')p=Find(x-
>right,k);
}
x->C='N';
returnp;
}
67
/*
* DeleteNodesinFibonnaciHeap
*/
68
intFibonacciHeap::Delete_key(node*H1,intk)
{
node* np =
NULL;intt;
t=Decrease_key(H1,k,-
5000);if(!t)
np=Extract_Min(H);i
f(np!= NULL)
cout<<"KeyDeleted"<<endl;
else
cout<<"Key not
Deleted"<<endl;return0;
}
/*
*MainContainsMenu
*/
intmain()
{
intn,m,l;Fibonacci
Heap fh;node*p;
node*H;
H=fh.InitializeHeap();
while(1)
{
cout<<" "<<endl;cout<
<"Operations on Binomial
heap"<<endl;cout<<" "<<endl;cout<<
"1)InsertElementintheheap"<<endl;
cout<<"2)Extract
Minimumkeynode"<<endl;cout<<"3)Decrease
keyofanode"<<endl;cout<<"4)Delete a
node"<<endl;cout<<"5)DisplayHeap"<<endl;
cout<<"6)Exit"<<endl;
cout<<"Enter Your Choice:
";cin>>l;
switch(l)
{
case1:
cout<<"Enter the element to be inserted:
";cin>>m;
p=
fh.Create_node(m);H =
fh.Insert(H, p);break;
case2:
p=
fh.Extract_Min(H);if(p
!=NULL)
cout<<"Thenodewithminimumkey:"<<p-
>n<<endl;else
cout<<"Heapisempty"<<endl;
69
break;
case3:
cout<<"Enterthekeytobedecreased:";cin
>>m;
cout<<"Enternewkeyvalue:";ci
n>>l;
fh.Decrease_key(H,m,l);
break;
case4:
cout<<"Enterthekeytobedeleted:";cin
>>m;
fh.Delete_key(H,
m);break;
case5:
cout<<"TheHeapis:"<<endl;f
h.Display(H);
break;
case6:
exit(1);
default:
cout<<"WrongChoice"<<endl;
}
}
return0;
}
Output
OperationsonBinomialheap
1)InsertElementintheheap
2)ExtractMinimumkeynode3)
Decreasekeyofanode4)Delete
anode
5)Display
Heap6)Exit
EnterYourChoice:1
Entertheelementtobeinserted:10
OperationsonBinomialheap
1)InsertElementintheheap
2)ExtractMinimumkeynode3)
Decreasekeyofanode4)Delete
anode
5)Display
Heap6)Exit
EnterYourChoice:1
Entertheelementtobeinserted:15
70
OperationsonBinomialheap
1)InsertElementintheheap
2)ExtractMinimumkeynode3)
Decreasekeyofanode4)Delete
anode
5)Display
Heap6)Exit
EnterYourChoice:1
Entertheelementtobeinserted:20
OperationsonBinomialheap
1)InsertElementintheheap
2)ExtractMinimumkeynode3)
Decreasekeyofanode4)Delete
anode
5)Display
Heap6)Exit
EnterYourChoice:5T
heHeapis:
TherootnodesofHeap
are:10-->15-->20
OperationsonBinomialheap
1)InsertElementintheheap
2)ExtractMinimumkeynode3)
Decreasekeyofanode4)Delete
anode
5) Display
Heap6)Exit
EnterYourChoice:3
Enterthekeytobedecreased:20Ent
ernewkey value:18
PSC:\Users\Administrator\Desktop\ADSArunningpgms>
71
EX:NO:8:GraphTraversals
Algorithm
DepthFirstSearchAlgorithm
Astandard DFSimplementationputseachvertex ofthegraph into oneoftwocategories:
1. Visited
2. NotVisited
Thepurposeofthealgorithmistomarkeachvertexasvisitedwhileavoidingcycles.TheDFSalgo
rithmworksasfollows:
1. Startby puttingany oneofthegraph'sverticeson topofastack.
2. Takethetopitemofthestack and additto thevisitedlist.
3. Createalistofthatvertex'sadjacentnodes. Addtheoneswhich
aren'tinthevisitedlisttothetopofthestack.
4. Keeprepeatingsteps2and3untilthestack isempty.
//C++programtoprintDFStraversalfrom
//
agivenvertexinagivengraph#incl
ude<bits/stdc++.h>
usingnamespacestd;
//Graphclassrepresentsadirectedgraph
//using
adjacencylistrepresentationclassGra
ph {
public:
map<int,bool>visited;m
ap<int,list<int>>adj;
//
functiontoaddanedgetographvoida
ddEdge(intv,intw);
//DFStraversalofthevertices
// reachable from
vvoidDFS(intv);
};
voidGraph::addEdge(intv,intw)
{
adj[v].push_back(w);//Addwtov’slist.
}
voidGraph::DFS(intv)
{
//Markthecurrentnodeasvisitedand
//
printitvisited[v]
=
72
true;cout<<v<<"
";
73
//Recurforalltheverticesadjacent
// to this
vertexlist<int>::ite
ratori;
for (i = adj[v].begin(); i != adj[v].end(); +
+i)if(!visited[*i])
DFS(*i);
}
//
Drivercodeint
main()
{
//
CreateagraphgivenintheabovediagramGraph
g;
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,2);
g.addEdge(2,0);
g.addEdge(2,3);
g.addEdge(3,3);
cout<<"FollowingisDepthFirstTraversal"
" (startingfromvertex2)\n";
g.DFS(2);
return0;
}
Output
2013
Algorithm
BFSalgorithm
Astandard BFSimplementationputseachvertexofthegraphintooneoftwocategories:
1. Visited
2. NotVisited
The purpose of the algorithm is to mark each vertex as visited whileavoiding
cycles.Thealgorithmworksasfollows:
1. Startby putting any oneofthegraph'sverticesattheback ofaqueue.
2. Takethefrontitemofthequeueandadditto thevisitedlist.
3. Createalistofthatvertex'sadjacentnodes.Add
theoneswhicharen'tinthevisitedlisttotheback ofthequeue.
4. Keeprepeating steps2 and3untilthequeueisempty.
The graph might have two different disconnected parts so to make sure that we cover
everyvertex,wecan alsoruntheBFSalgorithmoneverynode
74
//ProgramtoprintBFStraversalfromagiven
//sourcevertex.BFS(ints)traversesvertices
// reachable from
s.#include<iostrea
m>#include<list>
usingnamespacestd;
//Thisclassrepresentsadirectedgraphusing
//
adjacencylistrepresentationcla
ssGraph
{
intV;//No.ofvertices
//Pointertoanarraycontainingadjacency
//
listslist<int>*
public: adj;
Graph(intV);//Constructor
//
functiontoaddanedgetographvoida
ddEdge(intv,intw);
Graph::Graph(intV)
{
this->V=V;
adj=newlist<int>[V];
}
voidGraph::addEdge(intv,intw)
{
adj[v].push_back(w);//Add wtov’slist.
}
voidGraph::BFS(ints)
{
//
Markalltheverticesasnotvisitedbool*
visited=newbool[V];
for(inti=0;i<V;i++)
visited[i]=false;
//Createa
queueforBFSlist<int>que
ue;
75
//Markthecurrentnodeasvisitedand enqueueit
76
visited[s]=true;queu
e.push_back(s);
//'i'willbeusedtogetalladjacent
//
verticesofavertexlist
<int>::iteratori;
while(!queue.empty())
{
//Dequeueavertexfromqueueandprintits=
queue.front();
cout << s << "
";queue.pop_front
();
//Getalladjacentverticesofthedequeued
//vertexs.Ifaadjacenthasnotbeen visited,
//thenmarkitvisitedand enqueueit
for(i=adj[s].begin();i!=adj[s].end();++i)
{
if(!visited[*i])
{
visited[*i]=true;queu
e.push_back(*i);
}
}
}
}
//
Driverprogramtotestmethodsofgraphclassintmai
n()
{
//
CreateagraphgivenintheabovediagramGraph
g(4);
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,2);
g.addEdge(2,0);
g.addEdge(2,3);
g.addEdge(3,3);
cout<<"FollowingisBreadthFirstTraversal"
<<"(startingfromvertex2)\
n";g.BFS(2);
return0;
}
Output
77
2031
78
EX.NO:9:SpanningTreeImplementation
Algorithm
Aminimumspanningtreeisaspanningtreeinwhichthesumofthe
weightoftheedgesisasminimumaspossible.
Kruskal'salgorithm
We startfromtheedgeswiththelowestweightandkeepaddingedgesuntilwe reachourgoal.
ThestepsforimplementingKruskal'salgorithmareasfollows:
1. Sortalltheedgesfromlowweightto high
2. Take the edge with the lowest weight and add it to the spanning tree. If adding
theedgecreated acycle, then rejectthisedge.
3. Keep addingedgesuntilwereach allvertices.
//Creatingshortcutforan
integerpairtypedefpair<int,int> iPair;
//Structure
torepresentagraphstructGraph
{
intV,E;
vector<pair<int,iPair>>edges;
//
ConstructorGraph(
intV,intE)
{
this->V =
V;this->E
=E;
}
//
Utilityfunctiontoaddanedgevoid
addEdge(intu,intv,intw)
{
edges.push_back({w,{u,v}});
79
}
80
//Functiontofind MSTusingKruskal's
// MST
algorithmintkrusk
alMST();
};
//
TorepresentDisjointSetsstru
ctDisjointSets
{
int*parent,*rnk;i
ntn;
//
Constructor.DisjointSets
(intn)
{
//
Allocatememoryth
is->n=n;
parent=newint[n+1];r
nk=newint[n+1];
//Initially,allverticesarein
//
differentsetsandhaverank0.for(i
nti=0;i<=n;i++)
{
rnk[i]=0;
//Findtheparentofanode'u'
// Path
Compressionintfind
(intu)
{
/* Make the parent of the nodes in the
pathfromu-->parent[u]pointtoparent[u]*/
if (u!=parent[u])
parent[u] =
find(parent[u]);returnparent[u];
}
//Unionbyrank
voidmerge(intx,int y)
{
x=find(x),y=find(y);
81
/
*Maketreewithsmallerheightasu
btreeoftheothertree*/
if(rnk[x]>rnk[y])
parent[y]=x;
82
else//
Ifrnk[x]<=rnk[y]
parent[x]= y;
if(rnk[x]==rnk[y])
rnk[y]++;
}
};
/*FunctionsreturnsweightoftheMST*/
intGraph::kruskalMST()
{
intmst_wt=0;//Initializeresult
//
Sortedgesinincreasingorderonbasisofcostsort(ed
ges.begin(),edges.end());
// Create disjoint
setsDisjointSetsds(V
);
//Iteratethrough allsorted
edgesvector<pair<int,
iPair>>::iteratorit;
for(it=edges.begin();it!=edges.end();it++)
{
intu = it-
>second.first;intv=it-
>second.second;
intset_u=ds.find(u);in
tset_v=ds.find(v);
//Checkiftheselectededgeiscreating
//acycleornot(Cycleiscreatedifu
//
andvbelongtosameset)if(set_
u!=set_v)
{
//CurrentedgewillbeintheMST
// soprint it
cout<<u << "-"<< v <<endl;
//
UpdateMSTweightmst_wt
+=it->first;
//
Mergetwosetsds.merge
(set_u,set_v);
83
}
}
returnmst_wt;
}
84
//
Driverprogramtotestabovefunctionsintm
ain()
{
/* Let us create above shown
weightedandundirectedgraph */
intV=9,E=14;
Graphg(V,E);
//
makingaboveshowngraphg.a
ddEdge(0,1,4);
g.addEdge(0,7,8);
g.addEdge(1,2,8);
g.addEdge(1,7,11);
g.addEdge(2,3,7);
g.addEdge(2,8,2);
g.addEdge(2,5,4);
g.addEdge(3,4,9);
g.addEdge(3,5,14);
g.addEdge(4,5, 10);
g.addEdge(5,6,2);
g.addEdge(6,7,1);
g.addEdge(6,8,6);
g.addEdge(7,8,7);
cout<<"EdgesofMSTare\
n";intmst_wt=g.kruskalMST();
cout<<"\nWeightofMST is"<<mst_wt;
return0;
}
Output
EdgesofMSTare6
-7
2 -8
5 -6
0 -1
2 -5
2 -3
0 -7
3 -4
WeightofMSTis37
85
foreachvertexVinG
foreachedge(U,V)inG
tempDistance <- distance[U] + edge_weight(U,
V)iftempDistance< distance[V]
distance[V] <-
tempDistanceprevious[V]<-
U
foreachedge(U,V)inG
Ifdistance[U]+edge_weight(U,V)<distance[V}
Error:NegativeCycleExistsr
eturndistance[],previous[]
//AC++programforBellman-Ford'ssinglesource
//
shortestpathalgorithm.#include<
bits/stdc++.h>
//
astructuretorepresentaweightededgeingraphstructE
dge{
intsrc,dest,weight;
};
Graph;graph->V= V;
graph->E=E;
87
graph->edge = new
Edge[E];returngraph;
}
//Autilityfunctionused to
printthesolutionvoidprintArr(intdist[],intn)
{
printf("VertexDistancefromSource\
n");for(inti=0;i< n;++i)
printf("%d\t\t%d\n",i,dist[i]);
}
//Themainfunctionthatfindsshortestdistancesfromsrc
//toallotherverticesusingBellman-Fordalgorithm.The
// function also detects negative weight
cyclevoidBellmanFord(structGraph*graph,ints
rc)
{
int V = graph-
>V;int E = graph-
>E;intdist[V];
//Step1:Initializedistancesfromsrctoallother
//
verticesasINFINITEfor(
inti=0;i<V;i++)
dist[i] =
INT_MAX;dist[src]= 0;
//Step2:Relaxalledges|V|-1times.Asimple
//shortestpathfromsrctoanyothervertexcan have
//at-most|V|-1 edges
for(inti=1;i<=V-1;i++)
{for(intj=0;j<E;j++){
int u = graph-
>edge[j].src;intv=graph-
>edge[j].dest;
int weight = graph-
>edge[j].weight;if(dist[u]!
=INT_MAX
&&dist[u]
+weight<dist[v])dist[v]=dist[
u]+weight;
}
}
//Step3:checkfornegative-weightcycles.Theabove
//stepguaranteesshortestdistancesifgraphdoesn't
//containnegative weightcycle.Ifwegetashorter
//
path,thenthereisacycle.for(in
ti=0;i<E;i++){
88
int u = graph-
>edge[i].src;intv=graph-
>edge[i].dest;
int weight = graph-
>edge[i].weight;if(dist[u]!
=INT_MAX
89
&&dist[u]+weight<dist[v]){
printf("Graphcontainsnegativeweightcycle");re
turn;//Ifnegativecycleisdetected,simply
//return
}
}
printArr(dist,V);
return;
}
//
Driverprogramtotestabovefunctionsintm
ain()
{
/* Let us create the graph given in above example
*/intV=5;//Numberofverticesingraph
intE=8;//
NumberofedgesingraphstructGraph*grap
h=createGraph(V,E);
BellmanFord(graph,0);
return0;
}
Output
VertexDistancefromSource
0 0
1 -1
2 2
3 -2
4 1
10.B.Dijkstra'salgorithmAl
gorithm
function dijkstra(G,
S)foreachvertexVinG
distance[V] <-
infiniteprevious[V]<-
NULL
IfV!=S,add
VtoPriorityQueueQdistance[S]<-0
whileQISNOTEMPTY
U<-ExtractMINfromQ
foreachunvisitedneighbourVofU
tempDistance <- distance[U] + edge_weight(U,
V)iftempDistance< distance[V]
distance[V] <-
tempDistanceprevious[V]<-
U
returndistance[],previous[]
//AC++programforDijkstra'ssinglesourceshortestpathalgorithm.
//
Theprogramisforadjacencymatrixrepresentationofthegraph#include<i
ostream>
usingnamespacestd;#
91
include<limits.h>
92
//
Numberofverticesinthegraph#defi
neV9
//Initializeminvalue
intmin=INT_MAX,min_index;
returnmin_index;
}
// FunctionthatimplementsDijkstra'ssinglesourceshortestpathalgorithm
//
foragraphrepresentedusingadjacencymatrixrepresentationvoidd
ijkstra(intgraph[V][V],intsrc)
{
intdist[V];//Theoutputarray.dist[i]willholdtheshortest
//distancefromsrcto i
boolsptSet[V];//sptSet[i]willbe trueifvertexiisincludedinshortest
//pathtreeorshortestdistancefromsrctoiisfinalized
//
Distanceofsourcevertexfromitselfisalways0dist[sr
c]= 0;
//Find shortestpathforallvertices
for(intcount= 0;count< V-1;count++){
//Picktheminimumdistancevertexfromthesetofverticesnot
//yetprocessed.uisalwaysequaltosrcinthefirstiteration.intu =
93
minDistance(dist,sptSet);
94
//
MarkthepickedvertexasprocessedsptS
et[u]= true;
//Updatedistvalueoftheadjacentverticesofthepickedvertex.for(intv
= 0;v < V;v++)
//Updatedist[v]onlyifisnot insptSet,thereisanedgefrom
//utov, and totalweightofpathfromsrcto vthroughu is
//smallerthancurrentvalueofdist[v]
if (!sptSet[v] && graph[u][v] && dist[u] !=
INT_MAX&&dist[u]+graph[u][v]<dist[v])
dist[v]=dist[u]+graph[u][v];
}
//printthe
constructeddistancearrayprintSolutio
n(dist);
}
/*Letuscreatetheexamplegraphdiscussedabove*/
intgraph[V][V]= {{0,4,0, 0,0, 0,0, 8,0 },
{4, 0,8, 0, 0,0, 0, 11,0 },
{0, 8,0, 7, 0,4, 0, 0,2 },
{0, 0,7, 0,9, 14, 0,0, 0},
{0, 0,0, 9,0, 10, 0,0, 0},
{0, 0,4, 14, 10,0, 2, 0,0 },
{0, 0,0, 0, 0,2, 0, 1,6 },
{8, 11,0, 0, 0,0, 1, 0,7 },
{0, 0,2, 0, 0, 0,6, 7, 0}};
dijkstra(graph,0);
return0;
}
Output
VertexDistance from Source0
0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
95
EX.NO:11:ImplementationofMatrixChainMultiplication
Algorithm
matOrder(array,n)
Input−Listofmatrices,thenumberofmatricesinthelist.
Output−Minimumnumberofmatrixmultiplication.
Begin
define table minMul of size n x n, initiallyfill with all
0sforlength :=2 to n,do
for i:=1 to n-length,
doj := i + length –
1minMul[i,j] :=∞for
k:=itoj-1,do
q:=minMul[i,k]+minMul[k+1,j]+array[i-
1]*array[k]*array[j]ifq<minMul[i,j],thenminMul[i,j]:=q
done
done
done
returnminMul[1,n-
1]End
//SeetheCormenbookfordetailsofthe
//
followingalgorithm#incl
ude <bits/stdc+
+.h>usingnamespacestd;
//MatrixAihasdimensionp[i-1]xp[i]
//fori= 1..n
intMatrixChainOrder(intp[],intn)
{
inti,j,k,L,q;
//costiszerowhenmultiplying
//onematrix.
for(i= 1;i<n;i++)
m[i][i]=0;
96
//Lischainlength.
for(L= 2;L<n;L++)
{
for(i=1;i<n-L+1;i++)
{
j= i+ L-1;
m[i][j]=INT_MAX;
for(k= i;k <=j-1;k++)
{
//q=cost/
scalarmultiplicationsq=m[i][k]
+m[k+1][j]
+p[i-1]*p[k]*p[j];
if(q<m[i][j])
m[i][j]=q;
}
}
}
returnm[1][n-1];
}
//
DriverCodeint
main()
{
intarr[]={1,2,3,4};
intsize=sizeof(arr)/sizeof(arr[0]);
cout<<"Minimumnumber ofmultiplicationsis"
<<MatrixChainOrder(arr,size);
getchar();
return0;
}
Ouput
Minimum numberofmultiplicationsis18
97
EX.NO:12:ActivitySelectionandHuffmanCodingImplementat
ion
Algorithm
InputDatafortheAlgorithm:
act[]arraycontainingalltheactivities.
s[]arraycontainingthestartingtime ofalltheactivities.
f[]arraycontainingthe finishingtimeofalltheactivities.
OuputDatafromtheAlgorithm:
sol[]arrayreferingtothesolutionsetcontainingthemaximumnumberofnon-
conflictingactivities.
StepsforActivitySelectionProblem
Following are the steps we will be following to solve the activity selection
problem,Step 1: Sort the given activities in ascending order according to their
finishing time.Step2:Selectthefirstactivityfromsorted arrayact[]and add
ittosol[]array.
Step3:Repeatsteps4and5fortheremainingactivitiesinact[].
Step 4: If the start time of the currently selected activity is greater than or equal to the
finishtimeofpreviouslyselectedactivity,thenadd ittothesol[]array.
Step5:Selectthenextactivityinact[]array.
Step6:Printthesol[]array.
#include <bits/stdc+
+.h>usingnamespacestd;
#defineN6 //definesthenumberofactivities
//
Structurerepresentsanactivityhavingstarttimeandfinishtime.structActi
vity
{
intstart,finish;
};
//
ThisfunctionisusedforsortingactivitiesaccordingtofinishtimeboolSort_
activity(Activity s1, Activity s2)
{
return(s1.finish<s2.finish);
}
/* Printsmaximumnumberofactivitiesthatcan
be donebyasinglepersonorsinglemachineatatime.
*/
voidprint_Max_Activities(Activityarr[],intn)
{
//
Sortactivitiesaccordingtofinishtime
sort(arr,arr+n,Sort_activity);
98
cout<<"Followingactivitiesareselected\n";
99
//
Selectthefirstactivityinti
= 0;
cout<<"("<<arr[i].start<<","<<arr[i].finish<<")\n";
//Considertheremainingactivitiesfrom1 to n-
1for(intj= 1;j< n;j++)
{
//Selectthisactivityifithasstarttimegreaterthanorequal
//tothefinishtimeofpreviouslyselected
activityif(arr[j].start>=arr[i].finish)
{
cout<<"("<<arr[j].start<<","<<arr[j].finish<<")\n";i= j;
}
}
}
//
Driverprogramin
tmain()
{
Activityarr[N];
for(int i=0;i<=N-1; i++)
{
cout<<"Enterthestartandendtimeof"<<i+1<<"activity\
n";cin>>arr[i].start>>arr[i].finish;
}
print_Max_Activities(arr,N);r
eturn0;
}
Output
Enterthestart andendtimeof 1activity1 2
Enterthestart andendtimeof 2activity3 4
Enterthestart andendtimeof 3activity0 6
Enterthestart andendtimeof 4activity5 7
Enterthestartandendtimeof5activity5 9
Enterthestart andendtimeof 6activity8 9
Following activities are
selected(1,2)
(3,4)
(5,7)
(8,9)