UG - B.sc. - Computer Science - Data Structures and Algorithms Lab - 13034
UG - B.sc. - Computer Science - Data Structures and Algorithms Lab - 13034
(Accredited with ‘A+’ Grade by NAAC (with CGPA: 3.64) in the Third Cycle and Graded as
category - I University by MHRD-UGC)
(A State University Established by the Government of Tamilnadu)
All rights reserved. No part of this publication which is material protected by this copyright notice may be
reproduced or transmitted or utilized or stored in any form or by any means now known or hereinafter invented,
electronic, digital or mechanical, including photocopying, scanning, recording or by any information storage or
retrieval system, without prior written permission from the Alagappa University, Karaikudi, Tamil Nadu.
CONTENTS Page NO
UNIT – 2: 11-14
Control Structures: Using if and switch constructs Programs
UNIT – 3: 14-18
Looping , Arrays ,Structure statements: for, while, do-while, Strings and Matrices
Programs Problems
BLOCK 2 : OOPs CONCEPTS
UNIT – 4: 19-26
Functions: static function, friend function ,constructor , destructor and operator
overloading and Recursive programs
UNIT- 5: 26-31
Inheritance and polymorphism: Inheritance types and polymorphism types, Virtual
function
UNIT- 6: 32-34
File: File Handling C++ Programs, opening and closing a data file - creating a data file,
processing a data file.
UNIT- 7: 35-36
Pointers : Pointers and Pointers with Arrays Programs
BLOCK 3: LINEAR DATA STRUCUTURE
UNIT 8: 37-39
Stacks : Stack Implementation, expression evaluation, Polish notation
40-42
UNIT 9:
Queues: Queue Implementation, Applications of Queue
UNIT-10: 42-49
Linked List programs: List, Merging lists, Linked list, Single linked list, Double Linked
List, Header Linked list, Insertion and Deletion of linked list, Traversing a linked list.
50-62
UNIT 11:
Tree Programs : Trees, Binary Trees, Types of Binary trees, Binary Tree Representation,
Traversing Binary Trees, Binary Search tree, Insertion and Deletion operations,
63-78
UNIT 12:
Graphs:
Shortest Path Algorithms
o Dijkstra’s Algorithm
o Graphs with Negative Edge costs
o Acyclic Graphs
o All Pairs Shortest Paths Algorithm
Minimum cost Spanning Trees
o Kruskal’s Algorithm
o Prims’s Algorithm
o Applications
UNIT 13:
Searching Techniques: Linear and Binary search Programs
s
t
Self –instructional material a 2
n
d
a
Simple C++ programs
Through this app we can execute C++ programs.
[
How to open:
T Notes
y
p
e
t
h
e
s
i
d
e
b
a
r
c
o
n
t
e
Go to Start and search for Turbo C++: n
t
.
s
i
d
e
b
a
r
i
s
s
t
3 a
Self –instructional material
n
d
a
Simple C++ programs
In this app we have File menu:
[
Notes T
y
p
e
t
h
e
s
i
d
e
b
a
r
c
o
n
t
Edit menu:
e
n
t
.
s
i
d
e
b
a
r
i
s
s
t
Self –instructional material a 4
n
d
a
Simple C++ programs
Search Menu:
[
T Notes
y
p
e
t
h
e
s
i
d
e
b
a
r
Run Menu:
c
o
n
t
e
n
t
.
s
i
d
e
b
a
r
i
s
s
t
5 a
Self –instructional material
n
d
a
Simple C++ programs
[
Compile Menu:
Notes T
y
p
e
t
h
e
s
i
d
e
b
a
r
c
o
n
t
eDebug Menu:
n
t
.
s
i
d
e
b
a
r
i
s
s
t
Self –instructional material a 6
n
d
a
Simple C++ programs
Project Menu: [
T Notes
y
p
e
t
h
e
s
i
d
e
b
a
r
c
Option Menu: o
n
t
e
n
t
.
s
i
d
e
b
a
r
i
s
s
t
7 a
Self –instructional material
n
d
a
Simple C++ programs
Window Menu:
[
Notes T
y
p
e
t
h
e
s
i
d
e
b
a
r
c
o
n
t
eHelp Menu:
n
t
.
s
i
d
e
b
a
r
i
s
s
t
Self –instructional material a 8
n
d
a
Simple C++ programs
s
#include<iostream.h> i
int main() d
{ e
cout<<”Hello world”;
b
return 0;
} a
r
Output:
Hello world c
o
n
1.2Write a program in C++ to print an integer value:
t
e
#include<iostream> n
int main() t
{ .
int a;
cout<<”Enter integer\n”; A
cin>>a;
cout<<”Integer is ”<<a;
s
return 0;
} i
d
Output: e
Enter integer b
10 a
Integer is 10 r
i
1.3Write a program in C++ to add two numbers: s
a
#include<iostream.h>
int main()
{ s
int a,b,sum; t
9 a
Self –instructional material
n
d
a
Simple C++ programs cout<<”Enter the 1st number\n”;
cin>>a;
[ cout<<”Enter the 2nd number\n”;
Notes T cin>>b;
y sum=a+b;
p cout<<”Sum of two number ”<<a;
e return 0;
}
tOutput:
hEnter the 1st number
10
e
Enter the 2nd number
20
sSum of two number 30
i
d
e1.4Write a program in C++ to swap two numbers:
b
a
r#include<iostream>
int main()
{
c
int a,b,c;
o cout<<”Enter the 1st number\t”;
n cin>>a;
t cout<<”\nEnter the 2nd number\t”;
e cin>>b;
n c=a;
t a=b;
. b=c;
cout<<”First number is\t”<<a;
cout<<”\nSecond number is\t<<b;
A return 0;
}
s
i Output:
dEnter the first number 12
eEnter the second number 13
bFirst number is 13
a
Second number is 12
r
a#include<iostream>
int main()
s{
t int a,b;
Self –instructional material a 10
n
d
a
Simple C++ programs
cout<<”Enter the 1st number\t”;
cin>>a;
[
cout<<”\nEnter the 2nd number\t”;
cin>>b; T Notes
a=a+b; y
b=a-b; p
a=a-b; e
cout<<”First number is\t”<<a;
cout<<”\Second number is\t”<<b; t
return 0; h
}
e
Output:
s
Enter the first number 12
Enter the second number 13 i
First number is 13 d
Second number is 12 e
b
a
UNIT – 2 r
Control Structures using if and switch
c
constructs program o
n
2.1 The simple If statement: t
Write a program to find the negative number: e
n
t
#include<iostream> .
int main()
{ A
cout<<”Please enter a number:\n “;
int x;
cin>>x; s
// this program only checks if the number is negative or not i
if(x<0) d
{ e
cout<<”\nNegative”; b
} a
return 0; r
}
i
Output:
s
Please enter a number:
-10
Negative a
s
t
11 a
Self –instructional material
n
d
a
Simple C++ programs
s
t
Self –instructional material a 12
n
d
a
Simple C++ programs
else if(x>0)
{
[
cout<<”\nPositive\n”;
} T Notes
else y
{ p
cout<< “\nThe number is 0”; e
}
return 0; t
} h
e
Output:
Please enter a number:0
The number is 0 s
i
d
2.4Switch case: e
Write a program to find weekdays based on the given b
number: a
r
#include<iostream> c
int main() o
{ n
cout<<”Please enter a number between 1 and 7:\n “;
t
int x;
cin>>x; e
switch(num) n
{ t
case 1: .
cout<<”Sunday”;
break; A
case 2:
cout<<”Monday”;
s
break;
case 3: i
cout<<”Tuesday”; d
break; e
case 4: b
cout<<”Wednesday”; a
break; r
case 5:
cout<<”Thursday”;
i
break;
s
case 6:
cout<<”Friday”; a
break;
case 7: s
cout<<”Saturday”; t
13 a
Self –instructional material
n
d
a
Simple C++ programs break;
// optional
[ default:
Notes T cout<<”Invalid Input”;
y }
p return 0;
e}
tOutput:
Please enter a numer between 1 and 7:
h
1
e
Sunday
s
i UNIT – 3
d
e
Looping, Arrays, Structure statements:
b for, while, do-while, Strings and Matrices
a
r
Programs
c3.1 Write a Program to find factorial of a number using For
oLoop
n
t
e#include<iostream>
nint main()
{
t
int i ,n,factorial=1;
. cout<<"Enter a number:";
cin>>n;
A for(i=1;i<=n;i++)
{
s factorial=factorial*i;
i }
d cout<<"Factorial of "<<n<<" ="<<factorial;
return 0'
e
}
b
a
Output :
rEnter a number: 5
Factorial of 5 = 120
i
s3.2
Write a Program for Adam's Square Number Using
While Loop
a
s#include<iostream.h>
t#include<conio.h>
Self –instructional material a 14
n
d
a
Simple C++ programs
void main()
{
[
int n,ss1,r,s=0,ss,ns,sr,sum=0;
clrscr(); T Notes
cout<<"Enter a number:"; y
cin>>n; p
cout<<"\nGiven number is:"<<n; e
ns=n*n;
cout<<"\nSquare of given number is:"<<ns; t
while(n!=0) h
{
e
r=n%10;
n=n/10;
s=s*10+r; s
} i
cout<<"\nReverse of given number is:"<<s; d
ss=s*s; e
cout<<"\nSquare of reverse number is:"<<ss; b
while(ss!=0) a
{
r
sr=ss%10;
ss=ss/10;
sum=sum*10+sr; c
} o
cout<<"\nReverse of square is:"<<sum; n
if(ns==sum) t
{ e
cout<<"\nGiven number is adam's number"; n
} t
else
.
{
cout<<"\nNot an adam's number";
} A
getch();
s
} i
d
Output : e
Enter a number:12 b
Given number is:12
a
Square of given number is:144
r
Reverse of given number is:21
Square of reverse number is:441
Reverse of square is:144 i
Given number is adam's number s
Enter a number:23 a
Given number is:23
Square of given number is:529 s
Reverse of given number is:32
t
15 a
Self –instructional material
n
d
a
Simple C++ programs
Square of reverse number is:1024
[Reverse of square is:4201
Notes T
yNot an adam's number
p
e
3.3Write a program to print the sum of n natural numbers
using Do While Loop
t
h
e#include<iostream>
#include<conio.h>
sint main()
i{
d int n,i=1,s=0;
e
cout<<"Enter n:";
cin>>n;
b
do
a {
r s=s+i;
i++;
c }
o while(i<=n);
n cout<<"Sum="<<s;
t getch();
return 0;
e
}
n
t
Output :
. Enter n:8
Sum=36
A
i
s
s
t
Self –instructional material a 18
n
d
a
Oops concepts
char cust_name[20]; A
int acc_no;
int amount; s
int bal; i
char cust_address[20]; d
public: e
void get(); b
void balance();
a
void withdraw();
void disp(); r
}; i
void bank :: get(void) s
{
cout<<"\n Cust_Name"; a
cin>>cust_name;
cout<<"\n A/c_No";
s
cin>>acc_no;
t
19 a
Self –instructional material
n
d
a
Oops concepts
cout<<"\n Amount";
cin>>amount;
[ cout<<"\n Cust_Address";
Notes T cin>>cust_address;
y bal=0;
p bal=amount;
e}
void bank :: balance(void)
t{
cout<<"Balance"<<bal;
h
}
evoid bank :: withdraw()
{
s cout<<"\n Enter amount";
i cin>>amount;
d bal=bal-amount;
e}
bvoid bank :: disp()
{
a
if(bal<100)
r
{
cout<<"No withdrawl";
c }
o else
n {
t cout<<"\n Cust_Name:"<<cust_name<<"\n";
e cout<<"\n A/c_No:"<<acc_no<<"\n";
n
cout<<"\n Cust_Address:"<<cust_address<<"\n";
cout<<"\n Balance:"<<bal<<"\n";
t
}
.}
void main()
A{
clrscr();
s bank b;
i b.get();
d b.balance();
b.withdraw();
e
b.disp();
b getch();
a}
r
OUTPUT:
i Cust_Name: Elango
sA/c_No: 58585
Amount: 5000
aCust_Address: 4, gandhinagar, Trichy
Balance 5000
s
Enter amount: 2000
t
Self –instructional material a 20
n
d
a
Oops concepts
Cust_Name: Elango
A/c_No: 58585
[
Cust_Address: 4,gandhinagar, Trichy
Balance: 3000 T Notes
y
p
4.2 Write a Program Using Static Variable and Static e
Function
t
h
#include<iostream> e
class demo
{ s
private:
i
static int x;
static int y; d
public: e
static void print() b
{ a
cout<<"Value Of x : "<<x; r
cout<<"Value Of y : "<<y;
} c
};
o
int demo ::x=10;
int demo ::y=20; n
int main() t
{ e
demo ob; n
cout<<"Printing Through Object Name : "; t
ob.print(); .
cout<<"Printing Through Class Name : ";
demo::print(); A
return 0;
}
s
i
Output :
d
Printing Through Object Name :
Value of x :10 e
Value of y :20 b
Printing Through Class Name : a
Value of x :10 r
Value of y :20
i
Characteristics of Static Function: s
It is initialized to zero when the first object of it’s class is created
no other initialization is permitted. a
Only one copy of that member is created for the entire class and is
shared by all the object of the class. s
t
21 a
Self –instructional material
n
d
a
Oops concepts
It is visible only within the class but its life time is the entire
program.
[
Notes T
4.3Write a Program to find swapping of two values Using
y
Friend function
p
e
#include<iostream.h>
t#include<conio.h>
hclass B;
eclass A
{
private:
s
int x;
i
public:
d void setx()
e {
b cout<<"\n enter x";
a cin>>x;
r }
friend void swap (A,B);
};
c
o
class B
n{
t private:
e int y;
n public:
t void sety()
. {
cout<<"\n enter y";
cin>>y;
A
}
friend void swap (A,B);
s};
i
dvoid swap (A o1,B o2)
e{
b int temp;
a cout<<"\nBefore swapping:"<<x<<"\t"<<y;
temp=o1.x;
r
o1.x=o2.y;
o2.y=temp;
i cout<<"\nAfter swapping x="<<o1.x<<"y="<<o1.y;
s}
avoid main()
{
s A p;
t B q;
Self –instructional material a 22
n
d
a
Oops concepts
clrscr();
p.setx();
[
q.sety();
swap(p,q); T Notes
getch(); y
} p
e
OUTPUT
******** t
Enter x: 2 h
Enter y: 3
e
Before swapping
x=2 y=3 s
After swapping i
x=3 y=2 d
e
b
4.4Write a Program for Matrix Using Constructor and a
Destructor r
c
#include<iostream.h>
o
#include<conio.h>
class matrix n
{ t
int **p; e
int d1,d2; n
public: t
matrix(int x,int y); .
void getelement(int i,intj,int value)
{ A
p[i][j]=value;
}
int &putelement(int i,int j) s
{ i
return p[i][j]; d
} e
~matrix(); b
}; a
matrix::matrix(int x,int y) r
{
d1=x;
d2=y; i
p=new int *[d1]; s
for(int i=0;i<d1;i++)
p[i]=new int [d2]; a
}
matrix::~matrix() s
{ t
23 a
Self –instructional material
n
d
a
Oops concepts
for(int i=0;i<d1;i++)
delete p[i]; //row by row deletion
[ delete p; // Reference for that matrix is delelted.
Notes Tcout<<"\nDestroyed";
y
p}
evoid main()
{
t int m,n;
clrscr();
h
cout<<"\n Enter the size of matrix";
e cin>>m>>n;
matrix a(m,n);
s cout<<"\n Enter matrix elements row by row";
i int i,j,value;
d for(i=0;i<m;i++)
e for(j=0;j<n;j++)
b {
cin>>value;
a
a.getelement(i,j,value);
r
}
A
#include<iostream.h>
#include<conio.h>
s
class product
i{
d protected:
e int pno;
b float up,qty;
a char pname[20];
r public:
void get();
};
i
void product::get()
s
{
cout<<"\nEnterPno,Pname,Qty and Unit Price(in float):";
a cin>>pno>>pname>>qty>>up;
}
sclass calculation:public product
t{
Self –instructional material a 26
n
d
a
Oops concepts
protected:
float tot;
[
public:
void calc(); T Notes
}; y
void calculation::calc() p
{ e
tot=up*qty;
} t
class result:public calculation h
{
e
public:
void put();
}; s
void result::put() i
{ d
cout<<"\nPNo :"<<pno; e
cout<<"\nPName :"<<pname; b
cout<<"\nQty :"<<qty; a
cout<<"\nUPrice:"<<up;
r
cout<<"\nTotal:"<<tot;
}
void main() c
{ o
result o; n
clrscr(); t
o.get(); e
o.calc(); n
o.put(); t
getch();
.
}
Output: A
*********
Enter Pno,Pname,Qty and Unit Price(in float): s
101 LUX 2 12.50 i
PNo : 101 d
PName : LUX e
Qty : 2 b
UPrice : 12.50
a
Total : 25.00
r
Function Overloading:
i
s
Using a single function name to perform different type
of task is known as Function Overloading. a
s
t
27 a
Self –instructional material
n
d
a
Oops concepts
5.2 Write a program for volume of different shapes using
[function overloading
Notes T
y #include<iostream.h>
p #include<conio.h>
e class function
{
t
public:
float volume(int a)
h
{
e int cube;
cube=a*a*a;
s return(cube);
i }
d float volume(float a,float b)
e {
b float cylinder;
cylinder=3.14*a*a*b;
a
return(cylinder);
r }
float volume(int a,intb,int c)
c {
o int rectangle;
n rectangle=a*b*c;
t return(rectangle);
e }
double volume(double a)
n
{
t
double sphere;
. sphere=(4/3)*3.14*a*a;
return(sphere);
A }
};
svoid main()
i{
d function f;
int ch;
e
do
b {
a cout<<"\n 1.Cube";
r cout<<"\n 2.Cylinder";
cout<<"\n 3.Rectangle";
i cout<<"\n 4.Sphere";
s cout<<"\n 5.Exit";
cout<<"\n Enter your choice";
cin>>ch;
a
switch(ch)
{
s case 1:
t cout<<"\n cube="<<f.volume(3);
Self –instructional material a 28
n
d
a
Oops concepts
break;
case 2:
[
cout<<"\n cylinder="<<f.volume(3.0,2.0);
break; T Notes
case 3: y
cout<<"\n rectangle="<<f.volume(2,4,3); p
break; e
case 4:
cout<<"\n sphere="<<f.volume(4); t
break; h
}
e
}while(ch!=5);
getch();
} s
i
Output: d
1. Cube e
2. Cylinder b
3. Rectangle a
4. Sphere r
5. Exit
Enter your choice: 1
c
Cube: 27
o
Virtual Function: n
t
e
A virtual function a member function which is declared
within a base class and is redefined(Overridden) by n
derived class. t
They are mainly used to achieve Runtime polymorphism. .
Functions are declared with a virtual keyword in base
class. A
s
5.3Write a Program for Book Details Using Virtual
i
Function
d
e
#include<iostream.h> b
#include<conio.h> a
#include<string.h> r
class media
{ i
protected: s
char title[50];
float price;
a
public:
media(char *s,float a)
{ s
strcpy(title,s); t
29 a
Self –instructional material
n
d
a
Oops concepts
price=a;
}
[ virtual void disp() {}
Notes T };
y class book :public media
p {
e int pages;
public:
t book(char *s,floata,int p) : media(s,a)
{
h
pages=p;
e }
void disp();
s };
i class tape : public media
d {
e float time;
b public:
tape(char *s,floata,float t) : media(s,a)
a
{
r
time=t;
}
c void disp();
o };
n void book :: disp()
t {
e cout<<"\n title :\t"<<title;
n
cout<<"\n pages :\t"<<pages;
cout<<"\n price :\t"<<price;
t
}
. void tape :: disp()
{
A cout<<"\n title :\t"<<title;
cout<<"\n play time :\t"<<time<<"mins";
s cout<<"\n price :\t"<<price;
i }
d void main()
{
e
char *title=new char[30];
b float price,time;
a int pages;
r clrscr();
cout<<"\n **********************";
i cout<<"\n VIRTUAL FUNCTION:";
s cout<<"\n ***********************";
cout<<"\n \n enter book details";
cout<<"\n title";
a
cin>>title;
cout<<"\n price";
s cin>>price;
t cout<<"\n pages";
Self –instructional material a 30
n
d
a
Oops concepts
cin>>pages;
book book1(title , price , pages);
[
cout<<"\n enter tape details ";
cout<<"\n title"; T Notes
cin>>title; y
cout<<"\n price"; p
cin>>price; e
cout<<"\n play time(mins)";
cin>>time; t
tape tape1(title , price ,time); h
media * list[2];
e
list[0]=&book1;
list[1]=&tape1;
cout<<"\n media details"; s
cout<<"\n .....Book..........."; i
list[0]->disp(); d
cout<<"\n .....Tape............"; e
list[1]->disp(); b
getch(); a
}
r
Output: c
**********************************
o
VIRTUAL FUNCTION
********************************** n
Enter Book details t
Title: roja e
Price: 155 n
Pages: 256 t
.
Enter tape details
Title: vijay A
Price: 890
Playtime(mins): 45
s
Media details i
...........................Book............................. d
Title: roja e
Pages: 256 b
Price: 155 a
.............................Tape.............................. r
Title: vijay
Playtime: 45mins
Price: 890 i
s
s
t
31 a
Self –instructional material
n
d
a
Oops concepts
[ UNIT 6 FILE
Notes T
y Open a File :
p The first operation generally performed on an object of one of these
classes is to associate it to a real file. This procedure is known as to open
e
a file.
Syntax :
t open(filename,mode);
h Close a File:
e When we are finished with our input and output operations on a file
we shall close it is close a file.
s Syntax:
i myfile.close();
d
e 6.1 Write a Program for Student Details Using File
b Concepts
a
r
#include<iostream.h>
c #include<conio.h>
#include<fstream.h>
o
class student
n
{
t int rno,f,a;
e char name[25],res[25];
n float m[6],tot,avg;
t ofstream of;
. ifstream inf;
public:
A
student(int x)
{
a=x;
s of.open("data.txt",ios::out);
i }
d void get()
e {
b for(int i=0;i<a;i++)
a {
r cout<<"\nEnter the roll no:";
cin>>rno;
of<<rno<<endl;
i cout<<"\nEnter the name:";
s cin>>name;
of<<name<<endl;
a for(int i=1;i<=5;i++)
{
s cout<<"\nEnter the mark:"<<i<<":";
t cin>>m[i];
Self –instructional material a 32
n
d
a
Oops concepts
of<<m[i]<<endl;
}
[
calc();
} T Notes
of.close(); y
} p
void calc() e
{
tot=0; t
for(int l=1;l<=5;l++) h
tot=tot+m[l];
e
of<<tot<<endl;
avg=tot/5;
of<<avg<<endl; s
f=0; i
for(int a=1;a<=5;a++) d
{ e
if(m[a]>40) b
f=f+1; a
}
r
if(f==5)
of<<"Pass"<<endl;
else c
of<<"Fail"<<endl; o
} n
void disp() t
{ e
inf.open("data.txt"); n
cout<<”RNO\tName\tMark1\t Mark2\tMark3 t
<< \tMark4\tMark5\tTot\tAvg\tResult\n”;
.
for(int i=0;i<a;i++)
{
inf>>rno; A
inf>>name;
cout<<rno<<"\t"<<name<<endl; s
for(int j=1;j<=5;j++) i
{ d
inf>>m[i]; e
cout<<m[i]<<endl;
b
}
inf>>tot; a
cout<<tot<<"\t"; r
inf>>avg;
cout<<avg<<"\t"; i
inf>>res; s
cout<<res<<"\t";
} a
inf.close();
}
s
};
t
33 a
Self –instructional material
n
d
a
Oops concepts
void main()
{
[ int a;
Notes T clrscr();
y cout<<"\nEnter the no. of students:";
p cin>>a;
e student s(a);
s.get();
t s.disp();
getch();
h
}
e
Output:
s Enter the no. of students: 2
i Enter the name : Shahid
d Enter the roll no: 112
e Enter the mark1 : 50
b Enter the mark2 : 50
a Enter the mark3 : 50
r
Enter the mark4 : 50
Enter the mark5 : 50
c Enter the name : Priyanka
o Enter the roll no: 113
n Enter the mark1 : 70
t Enter the mark2 : 70
e Enter the mark3 : 70
n Enter the mark4 : 70
t Enter the mark5 : 70
.
RNO Name Mark1 Mark2 Mark3 Mark4 Mark5 Tot Avg
Result
A -----------------------------------------------------------------------------------------
--------
s 112 Shahid 50 50 50 50 50 250 50
i Pass
d 113 Priyanka 70 70 70 70 70 350 70
e Pass
b
a Input and Output Header Files In Files
r
Ofstream: Stream class to write on files
i Ifstream: Stream class to read from files
s fstream: Stream class to both read and write from/to files.
s
t
Self –instructional material a 34
n
d
a
Oops concepts
[
UNIT 7 POINTERS T Notes
y
7.1Write Program for Swapping Of Two Numbers Using
p
Pointers e
#include<iostream.h> t
#include<conio.h> h
void main() e
{
int *a,*b,*temp; s
cout<<"Enter a and b : "; i
cin>>*a>>*b; d
temp=a;
e
a=b;
b=temp; b
cout<<"After Swapping \n "; a
cout<<"a="<<*a<<"\n"<<"b="<<*b; r
getch();
} c
o
Output: n
Enter a and b :5 t
4 e
After Swapping
n
a=4
b=5 t
.
s
#include<iostream.h> i
#include<string.h> d
int main() e
{ b
int i=0;
a
char *p[10]={"cpp","java","c#","vb"};
char s[20]; r
cin>>s;
for(i=0;i<4;i++) i
{ s
if(strcmp(s,*p[i]))
{ a
cout<<"Book Name Exists";
break;
s
}
t
35 a
Self –instructional material
n
d
a
Oops concepts
}
if(i==4)
[ {
Notes T cout<<"Not Found";
y }
p return 0;
e}
tOutput :
hEnter Book Name :
ejava
Book Name Exists
C Programming
s
Not Found
i
d
e
b
a
r
c
o
n
t
e
n
t
.
s
i
d
e
b
a
r
i
s
s
t
Self –instructional material a 36
n
d
a
Linear data structure
BLOCK 3 [
T
LINEAR DATA STRUCTURE y
Notes
p
e
UNIT- 8 Stacks: Stack Implementation,
expression evaluation, Polish notation t
h
Stack Implementation in C++: e
A stack is a linear data structure than serves as a container of
objects that are inserted and removed according to the LIFO(last-in-first- s
out) rule. i
d
Below stack implementation in C++ covers below opertation:
e
1. push: Inserts a new element at the top of the stack, above its
b
current top element.
a
2. pop: Removes the top element on the stack, thereby
decrementing its size by one. r
3. isEmpty: Returns true if stack is empty i.e. its size is zero
else it returns false. c
4. isFull: Returns true if stack is full i.e. its size has reached o
maximum allocated capacity else it returns false. n
5. size: Returns the count of elements present in the stack. t
e
8.1 Stack using array n
t
.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h> A
int s[20],n,top;
void stack(); s
void push(); i
void pop(); d
void disp(); e
void main()
b
{
clrscr(); a
stack(); r
int ch;
do i
{ s
cout<<"\nEnter option->1.push 2.pop 3.display
4.exit:"; a
cin>>ch;
s
switch(ch)
{ t
a
37 n Self –instructional material
d
a
l
Linear data structure
case 1:push();break;
case 2:pop(); break;
[ case 3:disp();break;
Notes T default:exit(0);
y break;
p }
e }while(ch<=4);
}
t }
void stack()
h
{
e top=-1;
cout<<"Enter the size:";
s cin>>n;
i }
d void push()
e {
b int x;
if(top==n-1)
a
cout<<"\nStack is full";
r
else
{
c cout<<"\nEnter the element:";
o cin>>x;
n top++;
t s[top]=x;
e }
n
}
t
void pop()
. {
int x;
A if(top==-1)
cout<<"\nStack is empty";
s else
i {
d x=s[top];
top--;
e
cout<<"\n"<<x<<"is deleted from the stack\n";
b
}
a }
r
void disp()
i {
s int i;
if(top==-1)
cout<<"\nStack is empty";
a
else
{
s cout<<"\nElements of the stack are:\n";
t for(i=top;i>=0;i--)
a
n 38
Self –instructional material
d
a
l
Linear data structure
{
cout<<s[i];
[
cout<<endl;
} T Notes
} y
} p
e
Output :
Enter the size:3 t
Enter option->1.push 2.pop 3.display 4.exit:1 h
Enter the element:10 e
s
Expression evaluation:
This C++ program, using a stack data structure, computes value of i
postfix expression which pushes operands and pops these values on d
encountering an operator. e
b
Polish notation: a
Polish notation (PN), also known as normal Polish notation r
(NPN), Polish prefix notation or simply prefix notation, is a
mathematical notation in which operators precede their operands, in i
contrast to the more common infix notation, in which operators are placed s
between operands, as well as reverse Polish notation (RPN), in which
operators follow their operands. It does not need any parentheses as long
a
as each operator has a fixed number of operands.
s
t
a
39 n Self –instructional material
d
a
l
Linear data structure
UNIT 9
Queues: Queue Implementation,
Notes
Applications of Queue
Queue Implementation
A queue is an abstract data structure that contains a collection of
elements. Queue implements the FIFO mechanism i.e. the element that is
inserted first is also deleted first. In other words, the least recently added
element is removed firs in a queue.
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
class queue
{
int q[20],n,f,r,x,i;
public:
queue()
{
clrscr();
f=-1;
r=-1;
cout<<"\nEnter the n value: \t";
cin>>n;
}
void enqueue();
void dequeue();
void disp();
};
void queue::enqueue()
{
if(r==n-1)
{
cout<<"\nQueue is full"<<endl;
}
else
{
40
Self –instructional material
cout<<"Enter a element to queue: \t"; Linear data structure
cin>>x; [
if(f==-1) T
f=0; y Notes
r=r+1; p
q[r]=x;
e
}
}
void queue::dequeue() t
{ h
if (r==f==-1||r<f) e
{
cout<<"\nQueue is empty"<<endl; s
} i
else
d
{
cout<< "Deleted from the queue;"; e
x=q[f]; b
cout<<x<<endl; a
f=f+1; r
}
} c
void queue::disp() o
{
n
if(r==f==-1||r<f)
{ t
cout<<"\nQueue is empty"<<endl; e
} n
else t
{ .
cout<<"Elements of the queue are: ";
for(i=f;i<=r;i++) A
{
cout<<endl;
s
cout<<q[i];
} i
} d
}; e
void main() b
{ a
int ch; r
queue q;
clrscr();
i
cout<<"\t\t\tQUEUE\n";
do s
{
cout<<"\n\n1.Enqueue 2.Dequeue 3.Display 4.Exit\n"; a
cout<<"\nEnter your choice: \t";
cin>>ch; s
switch(ch) t
{ a
n
41 Self –instructional material
d
a
l
Linear data structure
case 1:
q.enqueue();
break;
case 2:
Notes q.dequeue();
break;
case 3:
q.disp();
break;
case 4:
exit(0);
default:
cout<<"\nEnter 1to4 values: ";
}
}while(1)
Output:
Queue
Enter the n value:
3
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:
1
Enter a element to queue
10
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:
1
Enter a element to queue
20
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:
1
Enter a element to queue
30
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:
1
Queue is full
UNIT 10
Linked List programs
List
A list or sequence is an abstract data type that represents a
countable number of ordered values, where the same value may occur
more than once. An instance of a list is a computer representation of the
mathematical concept of a finite sequence; the (potentially) infinite analog
of a list is a stream. Lists are a basic example of containers, as they
42
Self –instructional material
contain other values. If the same value occurs multiple times, each Linear data structure
occurrence is considered a distinct item. [
T
Merging lists y Notes
You’re given the pointer to the head nodes of two sorted linked p
lists. The data in both lists will be sorted in ascending order. Change the
e
next pointers to obtain a single, merged linked list which also has data in
ascending order. Either head pointer given may be null meaning that the
corresponding list is empty. t
h
e
10.1 Write a C++ program to merge two sorted linked lists
s
#include <bits/stdc++.h> i
class Node d
{ e
public: b
int data; a
Node* next; r
};
/* pull off the front node of the source and put it in dest */
c
void MoveNode(Node** destRef, Node** sourceRef);
/* Takes two lists sorted in increasing order, and splices o
their nodes together to make one big sorted list which is n
returned. */ t
Node* SortedMerge(Node* a, Node* b) e
{ n
Node dummy; t
Node* tail = &dummy; .
dummy.next = NULL;
while (1)
{ A
if (a == NULL)
{ s
tail->next = b; i
break; d
} e
else if (b == NULL) b
{
a
tail->next = a;
break; r
}
if (a->data <= b->data) i
MoveNode(&(tail->next), &a); s
else
MoveNode(&(tail->next), &b); a
tail = tail->next;
}
s
return(dummy.next);
t
}
void MoveNode(Node** destRef, Node** sourceRef) a
n
43 Self –instructional material
d
a
l
Linear data structure
{
Output:
Merged Linked List is:
2 3 5 10 15 20
44
Self –instructional material
Linear data structure
Linked List
A linked list is a linear data structure, in which the elements are [
not stored at contiguous memory locations. The elements in a linked list T
are linked using pointers . y Notes
p
In simple words, a linked list consists of nodes where each node e
contains a data field and a reference(link) to the next node in the list
t
Single linked list h
Singly linked list is a type of data structure that is made up of
e
nodes that are created using self-referential structures. Each of these
nodes contain two parts, namely the data and the reference to the next list
node. Only the reference to the first list node is required to access the s
whole linked list. This is known as the head. The last node in the list i
points to nothing so it stores NULL in that part. d
e
10.2 Program For Implement Singly Linked List b
a
r
#include <iostream>
using namespace std; c
struct Node
o
{
int data; n
struct Node *next; t
}; e
struct Node* head = NULL; n
void insert(int new_data) { t
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); .
new_node->data = new_data;
new_node->next = head;
A
head = new_node;
}
void display() { s
struct Node* ptr; i
ptr = head; d
while (ptr != NULL) { e
cout<<ptr->data <<" "; b
ptr = ptr->next; a
} r
}
int main()
{ i
insert(3); s
insert(1);
insert(7); a
insert(2);
insert(9); s
cout<<"The linked list is: "; t
display();
a
return 0;
n
45 Self –instructional material
d
a
l
Linear data structure
}
Output :
The linked list is: 9 2 7 1 3
Notes
Header linked list
A Header linked list is one more variant of linked list. In Header
linked list, we have a special node present at the beginning of the linked
list. This special node is used to store number of nodes present in the
linked list.
#include <iostream>
struct Node{
int num;
Node *next;
};
struct Node *head=NULL;
void insertNode(int n){
struct Node *newNode=new Node;
newNode->num=n;
newNode->next=head;
head=newNode;
}
void display(){
if(head==NULL){
cout<<"List is empty!"<<endl;
return;
}
struct Node *temp=head;
while(temp!=NULL){
cout<<temp->num<<" ";
temp=temp->next;
}
cout<<endl;
}
void deleteItem(){
if(head==NULL){
cout<<"List is empty!"<<endl;
return;
}
46
Self –instructional material
cout<<head->num<<" is removed."<<endl; Linear data structure
head=head->next; [
} T
int main() y Notes
{ p
display();
e
insertNode(10);
insertNode(20);
insertNode(30); t
insertNode(40); h
insertNode(50); e
display();
deleteItem(); deleteItem(); deleteItem(); deleteItem(); deleteItem(); s
deleteItem(); i
display();
d
return 0;
} e
Output b
List is empty! a
50 40 30 20 10 r
50 is removed.
40 is removed. c
30 is removed. o
20 is removed. n
10 is removed. t
List is empty!
e
List is empty!
n
t
Traversal in a List .
In this program the start pointer points to the beginning of the list A
and rear points to the last node
The function create_new_node() takes one parameter, allocates s
memory to create a new node and returns the pointer to the new node. i
(return type: node *)
d
The function insert_node() takes node * type pointer as argument
e
and inserts this node in the end of the list.
And the function traversal() takes node * type pointer as b
argument and displays the list from this pointer till the end of the list. a
r
48
Self –instructional material
void travers(node *np) Linear data structure
{ [
while(np != NULL) T
{ y Notes
cout<<np->info<<" -> "; p
np = np->next;
e
}
cout<<" !!\n";
} t
h
Here is the sample run of this C++ program e
Enter Information for the new node: 10
Want to enter more nodes ? (y/n)..y s
i
Enter Information for the new node: 20 d
Want to enter more nodes ? (y/n)..y e
b
Enter Information for the new node: 30
a
Want to enter more nodes ? (y/n)..y
r
Enter Information for the new node: 40
Want to enter more nodes ? (y/n)..y c
o
The list now is: n
10->20-> 30-> 40-> !! t
e
n
t
.
s
i
d
e
b
a
r
i
s
s
t
a
n
49 Self –instructional material
d
a
l
Non-linear data structure
BLOCK 4
NON-LINEAR DATASTRUCTURE
Notes
UNIT 11
Tree Programs
Tree:
A tree is a collection of nodes connected by directed (or undirected)
edges. A tree is a nonlinear data structure, compared to arrays, linked lists,
stacks and queues which are linear data structures.
Binary trees:
A binary tree is made of nodes, where each node contains a "left"
reference, a "right" reference, and a data element. The topmost node in the
tree is called the root. ... On the other hand, each node can be connected to
arbitrary number of nodes, called children. Nodes with no children are
called leaves, or external nodes.
18
/ \
15 30
/ \ / \
40 50 100 40
18
/ \
15 20
/ \
40 50
/ \
30 50
18
/ \
40 30
/ \
100 40
In a Full Binary, number of leaf nodes is number of internal nodes plus 1
L=I+1
a
Balanced Binary Tree
A binary tree is balanced if the height of the tree is O(Log n) s
where n is the number of nodes. For Example, AVL tree maintains
t
O(Log n) height by making sure that the difference between heights of
left and right sub trees is 1. Red-Black trees maintain O(Log n) height by a
n
51 Self –instructional material
d
a
l
making sure that the number of Black nodes on every root to leaf paths are
Non-linear data structure same and there are no adjacent red nodes. Balanced Binary Search trees are
performance wise good as they provide O(log n) time for search, insert and
delete.
10
/
20
\
30
\
40
Sequential
Representation of Binary Tree.
Link Representation of Binary Tree.
Representation of a node:
Node Representation
Example
Consider the binary tree T in the figure. A schematic diagram of the
linked list representation of T appears in the following figure. Observe that
each node is pictured with its three fields, and that the empty sub tree is
pictured by using x for null entries.
t
h
e
s
i
d
e
b
a
r
c
o
n
t
e
n
Binary Tree t
.
Binary tree node representations
A
Linked Representation of Binary Tree
s
2) Sequential representation of Binary Tree i
d
e
Let us consider that we have a tree T. let our tree T is a binary
b
tree that us complete binary tree. Then there is an efficient way of
representing T in the memory called the sequential representation or a
array representation of T. This representation uses only a linear array r
TREE as follows:
The root N of T is stored in TREE [1]. i
If a node occupies TREE [k] then its left child is stored in TREE [2 * k] s
and its right child is stored into TREE [2 * k + 1].
a
For Example:
Consider the following Tree: s
t
a
n
53 Self –instructional material
d
a
l
Non-linear data structure Sequential Representation of Binary Tree
Its sequential representation is as follow:
Linear data structures like arrays, stacks, queues and linked list have only
one way to read the data. But a hierarchical data structure like a tree can be
traversed in different ways.
Depending on the order in which we do this, there can be three types of
traversal.
Inorder traversal
1. First, visit all the nodes in the left subtree
2. Then the root node
3. Visit all the nodes in the right subtree
inorder(root->left)
display(root->data)
inorder(root->right)
Preorder traversal
1. Visit root node
2. Visit all the nodes in the left subtree
3. Visit all the nodes in the right subtree
display(root->data)
preorder(root->left)
preorder(root->right)
Postorder traversal
1. visit all the nodes in the left subtree
2. visit the root node
3. visit all the nodes in the right subtree
postorder(root->left)
postorder(root->right)
display(root->data)
t
h
e
Output:
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
Enter your choice:1
Enter your data:20
Continue Insertion(0/1):1
Enter your data:14
Continue Insertion(0/1):1
Enter your data:9
Continue Insertion(0/1):1
Enter your data:19
Continue Insertion(0/1):1
Enter your data:25
Continue Insertion(0/1):1
Enter your data:21
Continue Insertion(0/1):1
Enter your data:23
Continue Insertion(0/1):1
Enter your data:30
Continue Insertion(0/1):1
Enter your data:26
Continue Insertion(0/1):0
Self –instructional material 58
Resultant Binary Search Tree after insertion operation: Non-linear data structure
[
T
20 y
/ \ p Notes
14 25
e
/ \ / \
9 19 21 30
\ / t
23 26 h
e
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree s
3. Search Element in Binary Search Tree i
4. Inorder traversal
d
5. Exit
Enter your choice:4 e
Inorder Traversal: b
9 14 19 20 21 23 25 26 30 a
1. Insertion in Binary Search Tree r
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree c
4. Inorder traversal o
5. Exit
n
Enter your choice:2
Enter your data:9 t
e
Delete node 9 n
t
.
s
i
d
e
1. Insertion in Binary Search Tree b
2. Deletion in Binary Search Tree a
3. Search Element in Binary Search Tree r
4. Inorder traversal
5. Exit
Enter your choice:4 i
Inorder Traversal: s
14 19 20 21 23 25 26 30
1. Insertion in Binary Search Tree a
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree s
4. Inorder traversal t
5. Exit
a
Enter your choice:2
n
59 Self –instructional material
d
a
l
Enter your data:14
Non-linear data structure
Delete node 14
20
/ \
19 25
Notes / \
21 30
\ /
23 26
Delete node 30
20
/ \
19 25
/ \
21 26
\
23
21
/ \
19 25
/ / \
16 23 26
/ \
14 17
Notes
UNIT 12 Graphs
A Graph is a non-linear data structure consisting of nodes and edges. The
nodes are sometimes also referred to as vertices and the edges are lines or
arcs that connect any two nodes in the graph.
Dijkstra's Algorithm
Dijkstra's algorithm has many variants but the most common one is
to find the shortest paths from the source vertex to all other vertices in the
graph.
Algorithm Steps:
1. Set all vertices distances = infinity except for the source vertex,
set the source distance =0 .
2. Push the source vertex in a min-priority queue in the form
(distance , vertex), as the comparison in the min-priority queue
will be according to vertices distances.
3. Pop the vertex with the minimum distance from the priority
queue (at first the popped vertex = source).
4. Update the distances of the connected vertices to the popped
vertex in case of "current vertex distance + edge weight < next
vertex distance", then push the vertex
5. With the new distance to the priority queue.
6. If the popped vertex is visited before, just continue without using
it.
7. Apply the same algorithm again until the priority queue is empty.
12.1Dijkstra program
#include<iostream>
#include<climits>
using namespace std;
#define vertex 7
int minimumDist(int dist[], bool Dset[])
{
int min=INT_MAX,index;
for(int v=0;v<vertex;v++)
{
if(Dset[v]==false &&dist[v]<=min)
{
min=dist[v];
index=v;
}
}
return index;
Output :
64
Self –instructional material
Non-linear data structure
Notes
Graphs with Negative Edge costs
#include <iostream>
#include <vector>
#include <iomanip>
#include <climits>
using namespace std;
// Data structure to store graph edges
struct Edge
{
int source, dest, weight;
};
// Recurive Function to print path of given vertex v from
source vertex
void printPath(vector<int> const &parent, int v)
{
if (v < 0)
return;
printPath(parent, parent[v]);
cout<< v << " ";
}
// Function to run Bellman-Ford algorithm from given
source
void BellmanFord(vector<Edge> const &edges, int source, int N)
{
// count number of edges present in the graph
int E = edges.size();
vector<int> distance (N, INT_MAX);
distance[source] = 0;
vector<int> parent (N, -1);
int u, v, w, k = N;
Output :
66
Self –instructional material
Non-linear data structure
Notes
Distance of vertex 0 from the source is 0. It’s path is [0]
Distance of vertex 1 from the source is -1. It’s path is [01]
Distance of vertex 1 from the source is 2. It’s path is [012]
Distance of vertex 1 from the source is -2. It’s path is [0143]
Distance of vertex 1 from the source is 1. It’s path is [014]
Acyclic graph
Acyclic graph is a directed graph which contains a path from at
least one node back to itself. ... An acyclic graph is a directed graph which
contains absolutely no cycle, that is no node can be traversed back to itself.
12.3 Program For generate a random DAG (Directed
Acyclic Graph) for a given number of edges.
#include<iostream>
#include<stdlib.h>
// The maximum number of the vertex for the sample random graph.
#define NOV 20
using namespace std;
// A function to check for the cycle, on addition of a new edge in the
random graph.
bool CheckAcyclic(int edge[][2], int ed, bool check[], int v)
{
int i;
bool value;
// If the current vertex is visited already, then the graph contains
cycle.
if(check[v] == true)
{
return false;
}
else
{
check[v] = true;
// For each vertex, go for all the vertex connected to it.
for(i = ed; i>= 0; i--)
{
if(edge[i][0] == v)
{
return CheckAcyclic(edge, ed, check, edge[i][1]);
}
}
}
// In case, if the path ends then reassign the vertexes visited in that
path to false again.
check[v] = false;
if(i == 0)
Notes return true;
}
// A function to generate random graph.
void GenerateRandGraphs(int e)
{
int i, j, edge[e][2], count;
bool check[21];
// Build a connection between two random vertex.
i = 0;
while(i< e)
{
edge[i][0] = rand()%NOV+1;
edge[i][1] = rand()%NOV+1;
for(j = 1; j <= 20; j++)check[j] = false;
if(CheckAcyclic(edge, i, check, edge[i][0]) == true)
i++;
}
// Print the random graph.
cout<<"\nThe generated random random graph is: ";
for(i = 0; i< NOV; i++)
{
count = 0;
cout<<"\n\t"<<i+1<<"->{ ";
for(j = 0; j < e; j++)
{
if(edge[j][0] == i+1)
{
cout<<edge[j][1]<<" ";
count++;
}
else if(edge[j][1] == i+1)
{
count++;
}
else if(j == e-1 && count == 0)
cout<<"Isolated Vertex!";
}
cout<<" }";
}
}
int main()
{
int e;
cout<<"Enter the number of edges for the random graphs: ";
cin>>e;
// A function to generate a random undirected graph
with e edges.
GenerateRandGraphs(e);
}
68
Self –instructional material
Non-linear data structure
Notes
Case 2:
Enter the number of edges for the random graphs: 50
#include<iostream>
#include<conio.h>
using namespace std;
int min(int a,int b);
int cost[10][10],a[10][10],i,j,k,c;
int main()
{
int n,m;
cout<<"Enter no of vertices";
cin>> n;
cout<<"Enter no od edges";
cin>> m;
cout<<"Ebter the\nEDGE Cost\n";
for(k=1;k<=m;k++)
{
cin>>i>>j>>c;
a[i][j]=cost[i][j]=c;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(a[i][j]== 0 &&i !=j)
a[i][j]=31999;
}
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=min(a[i][j],a[i][k]+a[k][j]);
cout<<"Resultant adj matrix\n";
for(i=1;i<=n;i++)
{
for( j=1;j<=n;j++)
{
if(a[i][j] !=31999)
cout<< a[i][j] <<" ";
70
Self –instructional material
Non-linear data structure
Notes
}
cout<<"\n";
}
getch();
}
int min(int a,int b)
{
if(a<b)
return a;
else
return b;
}
Output :
Enter no of vertices3
Enter no od edges5
Enter the
EDGE Cost
124
216
1 3 11
313
232
Resultant adj matrix
046
502
370
Kruskal's algorithm
Kruskal's algorithm is a minimum-spanning-tree algorithm which
finds an edge of the least possible weight that connects any two trees in the
forest. It is a greedy algorithm in graph theory as it finds a minimum
spanning tree for a connected weighted graph adding increasing cost arcs
at each step.
#include <bits/stdc++.h>
using namespace std;
// a structure to represent a weighted edge in graph
class Edge
{
public:
int src, dest, weight;
};
// a structure to represent a connected, undirected
// and weighted graph
class Graph
{
public:
// V-> Number of vertices, E-> Number of edges
int V, E;
// graph is represented as an array of edges.
// Since the graph is undirected, the edge
// from src to dest is also edge from dest
// to src. Both are counted as 1 edge here.
Edge* edge;
};
// Creates a graph with V vertices and E edges
Graph* createGraph(int V, int E)
{
Graph* graph = new Graph;
graph->V = V;
graph->E = E;
graph->edge = new Edge[E];
return graph;
}
// A structure to represent a subset for union-find
72
Self –instructional material
Non-linear data structure
Notes
class subset
{
public:
int parent;
int rank;
};
// A utility function to find set of an element i
// (uses path compression technique)
int find(subset subsets[], int i)
{
// find root and make root as parent of i
// (path compression)
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
// A function that does union of two sets of x and y
// (uses union by rank)
void Union(subset subsets[], int x, int y)
{
int xroot = find(subsets, x);
int yroot = find(subsets, y);
// Attach smaller rank tree under root of high
// rank tree (Union by Rank)
if (subsets[xroot].rank< subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank> subsets[yroot].rank)
subsets[yroot].parent = xroot;
// If ranks are same, then make one as root and
// increment its rank by one
else
{
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
// Compare two edges according to their weights.
// Used in qsort() for sorting an array of edges
int myComp(const void* a, const void* b)
{
Edge* a1 = (Edge*)a;
Edge* b1 = (Edge*)b;
return a1->weight > b1->weight;
}
// The main function to construct MST using Kruskal's
algorithm
void KruskalMST(Graph* graph)
{
int V = graph->V;
74
Self –instructional material
Non-linear data structure
Notes
// add edge 1-3
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 15;
// add edge 2-3
graph->edge[4].src = 2;
graph->edge[4].dest = 3;
graph->edge[4].weight = 4;
KruskalMST(graph);
return 0;
}
Output:
Following are the edges in the constructed MST
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Prims algorithm
Prim's algorithm is a greedy algorithm that finds a minimum
spanning tree for a connected weighted undirected graph. It finds a subset
of the edges that forms a tree that includes every vertex, where the total
weight of all the edges in the tree is minimized.
#include <iostream>
#include <cstring>
using namespace std;
#define INF 9999999
#define V 5
int G[V][V] = {
{0, 9, 75, 0, 0},
{9, 0, 95, 19, 42},
{75, 95, 0, 51, 66},
{0, 19, 51, 0, 31},
{0, 42, 66, 31, 0}
};
int main()
{
int no_edge;
int selected[V];
memset (selected, false, sizeof (selected));
}
}
}
}
cout<< x << " - " << y << " : " << G[x][y];
cout<<endl;
selected[y] = true;
no_edge++;
}
return 0;
}
Output:
Edge : Weight
0-1: 9
1 - 3 : 19
3 - 4 : 31
3 - 2 : 51
76
Self –instructional material
Non-linear data structure
Notes
12.7Programs for the implementation of BFS for a given
graph
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int cost[10][10],i,j,k,n,qu[10],front,rare,v,visit[10],visited[10];
main()
{
int m;
cout<<"Enterno of vertices";
cin>> n;
cout<<"Enter 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;
qu[rare++]=j;
}
v=qu[front++];
cout<<v << " ";
k++;
visit[v]=0; visited[v]=1;
}
}
Output :
Enterno of vertices9
Enter no of edges9
EDGES
78
Self –instructional material
Searching And Sorting
Algorithms
BLOCK 5 SEARCHING AND SORTING
ALGORITHMS
Notes
UNIT 13 Searching Techniques: Linear
and Binary search Programs
Linear Search
A Linear Search is the most basic type of searching algorithm. A
Linear Search sequentially moves through your collection (or data
structure) looking for a matching value. In other words, it looks down a
list, one item at a time, without jumping. Think of it as a way of finding
your way in a phonebook.
#include<iostream.h>
#include<conio.h>
class linear
{
int data[50],x;
int i,n;
public:
void get();
void search();
};
void linear::get()
{
cout<<"Enter n value:\t";
cin>>n;
cout<<"Enter the "<<n<<" values....\n";
for(i=0;i<n;i++)
{
cin>>data[i];
}
}
void linear::search()
{
int y,f=0;
cout<<"\nEnter the value to search:";
cin>>y;
void main()
{
clrscr();
linear ob;
ob.get();
ob.search();
getch();
}
Output
======
Enter n value: 5
Enter the 5 values.... 1 2 3 4 5
Binary Search
Binary search is a fast search algorithm with run-time complexity
of Ο(log n). ... For this algorithm to work properly, the data collection
should be in the sorted form. Binary search looks for a particular item by
comparing the middle most item of the collection. If a match occurs, then
the index of item is returned.
13.2Program for Binary Search
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class binary
{
80
Self –instructional material
int i,n,a[10],low,high,t,j,flag,x,mid; Searching And Sorting
Algorithms
public:
void getdata();
void sorting();
void searching();
};
void binary::getdata() Notes
{
cout<<"\nEnter the n values:\t";
cin>>n;
cout<<"\nEnter the elements one by one:\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}
}
void binary::sorting()
{
for(i=0;i<n;i++)
{
for(j=n-1;j>i;j--)
{
if(a[j]<a[j-1])
{
t=a[j];
a[j]=a[j-1];
a[j-1]=t;
}
}
}
cout<<"\nAfter sorting:\t";
for (i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
}
void binary::searching()
{
int x;
flag=1;
low=0;
high=n-1;
cout<<"\n\nEnter the searching element:\t";
cin>>x;
while(low<=high)
{
mid=(low+high)/2;
if(x<a[mid])
{
Output:
BINARY SEARCH
Enter the n values:
5
Enter the elements one by one:
50
30
10
20
40
After Sorting
10 20 30 40 50
Enter the search element
40
The required Element 40 is found
82
Self –instructional material
Searching And Sorting
Algorithms
UNIT 14
Sorting techniques:Bubble sort,Quick
sort,Insertion sort,Merge sort
Notes
Bubble sort:
Bubble sort, sometimes referred to as sinking sort, is a simple
sorting algorithm that repeatedly steps through the list, compares adjacent
pairs and swaps them if they are in the wrong order. The pass through the
list is repeated until the list is sorted.
14.1 Program for BUBBLE SORT
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class bubble
{
int i,j,k,n,data[20],t;
public:
void getdata();
void calculation();
void display();
};
void bubble::getdata()
{
cout<<"Enter the value of n:\t";
cin>>n;
cout<<"Enter the elements:\n";
for(i=0;i<n;i++)
{
cin>>data[i];
}
}
void bubble::calculation()
{
for(i=0;i<n;i++)
{
for(j=n-1;j>i;j--)
{
if(data[j]<data[j-1])
{
t=data[j];
data[j]=data[j-1];
data[j-1]=t;
Output:
BUBBLE SORT
Enter the value of n:
5
Enter the elements:
2
8
5
6
1
After 0 iteration
28516
After 0 iteration
28156
After 0 iteration
21856
After 0 iteration
12856
After 1 iteration
12856
After 1 iteration
12586
After 1 iteration
84
Self –instructional material
12586 Searching And Sorting
Algorithms
After 2 iteration
12568
After 3 iteration
12568
After Sorting
12568 Notes
Quick sort:
Quick sort is one of the most famous sorting algorithms based on
divide and conquers strategy which results in an O(n log n) complexity. So,
the algorithm starts by picking a single item which is called pivot and
moving all smaller items before it, while all greater elements in the later
portion of the list.
#include<iostream.h>
#include<conio.h>
void main()
{
void quicksort(int [],int,int);
int data[50],i,lb,mb;
clrscr();
cout<<"\t\t\tQUICK SORT\n";
cout<<"\n\nEnter n value:\t";
cin>>n;
cout<<"\n\nEnter the "<<n<<" elements...\n";
for(i=0;i<n;i++)
{
cin>>data[i];
}
quicksort(data,0,n-1);
cout<<"\n\n\nSorted array....\n";
for(i=0;i<n;i++)
{
cout<<data[i]<<endl;
}
getch();
}
void quicksort(int data[],int lb,int mb)
{
int flag,low,high,pivot,t;
if(lb<mb)
{
flag=1;
/*OUTPUT
QUICK SORT
Enter n value: 5
After 1 iteration.....
3 6 12 65 18
After 2 iteration....
3 6 12 65 18
After 3 iteration
86
Self –instructional material
3 6 12 18 65 Searching And Sorting
Algorithms
Sorted array..
3
6
12
18 Notes
65
Insertion Sort
Insertion sort is based on the idea that one element from the input
elements is consumed in each iteration to find its correct position i.e., the
position to which it belongs in a sorted array. Since is the first element has
no other element to be compared with, it remains at its position.
Following C++ program ask to the user to enter array size and array
element to sort the array using insertion sort technique, then display the
sorted array on the screen:
#include<iostream.h>
#include<conio.h>
class sort
{
int data[50],n,i,j,t;
public:
void get();
void sort();
void display();
};
void sort::get()
{
cout<<"\nEnter n value:\t";
cin>>n;
cout<<"\n\nEnter the "<<n<<" elements...\n";
for(i=0;i<n;i++)
{
cin>>data[i];
}
}
void sort::sort()
{
for(i=1;i<=n;i++)
Insertion sort
Enter n value: 5
Enter the 5 Elements
15 20 5 8 12
After 1 iteration
15 20 5 8 12
After 2 iteration
15 15 20 8 12
After 3 iteration
5 15 15 20 12
After 4 iteration
5 8 15 15 20
After 5 iteration
5 8 12 15 20
After sorting
5 8 12 15 20
88
Self –instructional material
Searching And Sorting
Merge sort Algorithms
Merge sort is a divide-and-conquer algorithm based on the idea of
breaking down a list into several sub-lists until each sublist consists of a
single element and merging those sublists in a manner that results into a
sorted list. Idea: Divide the unsorted list into sublists, each containing
element. Notes
#include<iostream.h>
#include<conio.h>
int n,data[50];
void merge(int data[],int low,intmid,int high)
{
int i,j,k,b[50],h;
i=low;
h=low;
j=mid+1;
while(h<=mid && j<=high)
{
if(data[h]<=data[j])
{
b[i]=data[h];
h++;
}
else
{
b[i]=data[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=data[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=data[k];
i++;
for(i=low;i<=high;i++)
Notes
{
cout<<data[i]<<" ";
}
cout<<endl;
}
void disp()
{
for(int i=0;i<n;i++)
{
cout<<data[i]<<"\t";
}
cout<<endl;
}
void mergesort(int data[],int low,int high)
{
static int i=1;
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(data,low,mid);
mergesort(data,mid+1,high);
merge(data,low,mid,high);
cout<<"\nAfter "<<i<<" iteration:\t";
i++;
disp();
}
}
void main()
{
int i;
clrscr();
cout<<”Merge Sort”<<endl;
cout<<"\nEnter n value:\t";
cin>>n;
cout<<"\nEnter the "<<n<<" elements.....\n";
for(i=0;i<n;i++)
{
cin>>data[i];
}
mergesort(data,0,n-1);
cout<<"\n\nSorted array.....\n\n";
90
Self –instructional material
disp(); Searching And Sorting
Algorithms
getch();
}
Output
Merge Sort
Enter n value: 5 Notes
Enter the 5 elements
6 5 7 1 4
5 6
After 1 iteration: 5 6 7 1 4
5 6 7
After 2 iteration: 5 6 7 1 4
1 4
After 3 iteration: 5 6 7 1 4
1 4 5 6 7
After 4 iteration: 1 4 5 6 7
Sorted array
1 4 5 6 7