Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
47 views

UG - B.sc. - Computer Science - Data Structures and Algorithms Lab - 13034

Uploaded by

veera jothimani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

UG - B.sc. - Computer Science - Data Structures and Algorithms Lab - 13034

Uploaded by

veera jothimani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 95

ALAGAPPA UNIVERSITY

(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)

KARAIKUDI – 630 003

DIRECTORATE OF DISTANCE EDUCATION

B.Sc. (COMPUTER SCIENCE)

Second Year – Third Semester

13034 – DATA STRUCTURE AND ALGORITHIM

Copy Right Reserved For Private Use only


Author:
Dr. A. Sumathi,
Assistant Processor,
Department of Computer Science,
SRC, Sastra University,
Kumbakonam -612 001.

“The Copyright shall be vested with Alagappa University”

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

BLOCK 1 : SIMPLE C++ PROGRAMS

UNIT -1: 9-11


Introduction Simple C++ Programs

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.

BLOCK 4 : NON LINEAR DATA STRUCTURE

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

BLOCK 5 : SEARCHING AND SORTING ALGORITHMS 79-82

UNIT 13:
Searching Techniques: Linear and Binary search Programs

UNIT 14: 83-91


Sorting techniques: Bubble sort, Quick sort, Insertion sort, Merge sort
Simple C++ programs
C++ Introduction
[
C++ is a multi-paradigm programming language that supports T Notes
object-oriented programming (OOP), created by Bjarne y
Stroustrup in 1983 at Bell Labs, C++ is an extension(superset) of C p
programming and the programs are written in C language can run in C++ e
compilers.
t
Uses of C++
h
C++ is used by programmers to create computer software. It is e
used to create general systems software, drivers for various computer
devices, software for servers and software for specific applications and s
also widely used in the creation of video games. i
C++ is used by many programmers of different types and coming from d
different fields. C++ is mostly used to write device driver e
programs, system software, and applications that depend on b
direct hardware manipulation under real-time constraints. It is also used
a
to teach the basics of object-oriented features because it is simple and is
also used in the fields of research. Also, many primary user r
interfaces and system files of Windows and Macintosh are written using
C++. So, C++ is a popular, strong and frequently used programming c
language of this modern programming era. o
n
Object-oriented programming and C++ t
e
C++ supports Object-Oriented Programming (OOP), with four n
significant principles of object-oriented development: t
 Abstraction .
 Encapsulation
 Inheritance A
 Polymorphism
s
Abstraction
i
d
Data abstraction allows a program to ignore the details of how a
data type is represented. Abstraction refersto the act of representing e
essential features without including the background details or b
explanations. a
r
Encapsulation
i
Unable to deal with the complexity of an object, human chooses s
to ignore its non-essential details and concentrate on the details which are
essential to our understanding. You can place a simple context of the a
object model, that abstraction is "looking for what you want" within an
object or class. But there is another major concept connected to
abstraction which is called encapsulation. s
t
1 a
Self –instructional material
n
d
a
Simple C++ programs So basically, encapsulation can be defined as the process of hiding
all of the details of an object that do not throw in or dealt with its essential
[characteristics. Encapsulation can also be defined as preventing access to
Notes Tnon-essential details of classes or its objects. Abstraction and encapsulation
yhave close bonding among each other. Encapsulation assists abstraction by
pproviding a means of suppressing the non-essential details.
e
Inheritance
t
h The technique of deriving a new class from an old one is called
inheritance. The old class is referred to as base class and the new class is
e
referred to as derived class or subclass. Inheritance concept allows
programmers to define a class in terms of another class, which makes
screating and maintaining application easier. When writing a new class,
i instead of writing new data member and member functions all over again,
dprogrammers can make a bonding of the new class with the old one that the
enew class should inherit the members of the existing class. A class can get
bderived from one or more classes, which means that it can inherit data and
afunctions from multiple base classes.
r
Here is the syntax how inheritance is performed in C++:
c
oclass derived-class: visibility-mode base-class
n
t
ePolymorphism
n
Polymorphism is another concept of object-oriented programming
t
(OOPs). The attitude which lies beneath this concept is "single interface
. having multiple implementations." This provides a single interface for
controlling access to a general class of actions. Polymorphism can be
Agained in both ways:
 Compile time
s  Run time
i
d A common and simple example of polymorphism is when you
used >> and << as operator overloading in C++,
e
for cin and cout statements respectively. This bitwise shift operator at that
b
time acts as a inclusion operator and its overloaded meaning is defined
ain iostream header file.
r
How to execute C++ program:
i
s

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

BLOCK – I SIMPLE C++ PROGRAMS [


T Notes
y
UNIT 1 p
e
Introduction: Simple C++ Programs
t
1.1 Write a program in C++ to print a message on output h
screen: e

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

1.5Write a program in C++ to swap two numbers without


i
the
help of third variable:
s

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

[2.2 If – Else control structure


Notes TWrite a program to find whether the given number is
ynegative or not:
p
e
#include<iostream>
int main()
t
{
h cout<<”Please enter a number:\n “;
e int x;
cin>>x;
s // this program only checks if the number is negative or not
i if(x<0)
d {
e cout<<”\nNegative\n”;
}
b
else
a
{
r cout<<”\nThe number is not negative”;
}
c return 0;
o }
nOutput:
tPlease enter a number:
e10
nThe number is not negative
t
.
2.3If – Else – Else If controls structure:
A
Write a program to find whether the given number is
positive or negative or zero:
s
i
d#include<iostream>
eint main()
b{
a cout<<”Please enter a number:\n “;
r int x;
cin>>x;
// this program only checks if the number is negative or not
i
if(x<0)
s {
cout<<”\nNegative\n”;
a }

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

3.4Write a program to Find Sum of n Array Elements


s
i
d#include<iostream>
e#include<conio.h>
bvoid main()
a{
r int arr[30],i,n,sum=0;
cout<<"Enter n:";
cin>>n;
i
cout<<"Enter "<<n<<" numbers :";
s
for(i=0;i<n;i++)
{
a cin>>arr[i];
}
s for(i=0;i<n;i++)
t {
Self –instructional material a 16
n
d
a
Simple C++ programs
sum=sum+arr[i];
}
[
for(i=0;i<n;i++)
{ T Notes
cout<<"Sum of Numbers =" <<sum; y
} p
getch(); e
}
t
Output: h
Enter n : 5 e
Enter 5 numbers :
75789
s
Sum of Number = 36
i
3.5Write a program to Count Word in Sentence Using d
String e
b
#include<iostream.h> a
#include<conio.h> r
#include<string.h>
#include<Stdio.h> c
void main() o
{ n
char strs[100],count=0,strw[20];
t
int i,len;
cout<<"Enter a Sentence : "; e
gets(strs); n
len=strlen(strs); t
for(i=0;i<len;i++) .
{
if(strs[i]==' ') A
{
count++;
s
} i
} d
cout<<"Total Num Of Words : "<<count+1; e
getch(); b
} a
Output: r
Enter a Sentence : Hello cpp Program how are you
Total Num Of Words : 6 i
s
3.6Write a Program for Transpose of Matrix
a
#include<iostream>
int main() s
{ t
17 a
Self –instructional material
n
d
a
Simple C++ programs int a[10][10],m,n,i,j;
cout<<"Enter Rows and Columns : ";
[ cin>>m>>n;
Notes T cout<<"Enter Matrix Elements : ";
y for(i=0;i<m;i++)
p {
e for(j=0;j<n;j++)
{
t cin>>a[i][j];
}
h
}
e cout<<"Your Matrix : \n ";
for(i=0;i<m;i++)
s {
i for(j=0;j<n;j++)
d {
e cout<<a[i][j]<<" ";
b cout<<"\n";
}
a
}
r
cout<<"Transpose Matrix : \n ";
for(i=0;i<n;i++)
c {
o for(j=0;j<m;j++)
n {
t cout<<a[i][j]<<" ";
e cout<<"\n";
n
}
}
t
return 0;
.}
Output :
AEnter Rows and Columns : 2 2
Enter Matrix Elements : 1 2 3 4
sYour Matrix :
i 12
d3 4
eTranspose Matrix :
1 3
b
2 4
a
r

i
s

s
t
Self –instructional material a 18
n
d
a
Oops concepts

BLOCK -2 OOPS CONCEPTS [


T Notes
y
UNIT – 4 p
Functions: static function, friend e

function, constructor, destructor and t


operator overloading and Recursive h
e
programs.
s
Public and Private Keywords: i
d
Public: e
Public members can be accessed by any other code(members) in b
the same class or other classes that references it. a
Private: r
Private members can be accessed only by code in the same class
or struct. c
o
4.1 Use of Class: Program for Transaction in Bank n
t
e
#include<iostream.h> n
#include<conio.h> t
class bank
.
{

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
}

c cout<<”\n”<<a.putelement(1,1)<<"is the element in the 1st


orow 1st column";
n }
t getch();
e }
n
tOutput:
. Enter the size of matrix: 3 3
Enter matrix elements row by row
7 8 9
A
2 3 4
5 6 7
s3 is the element in the 1st row 1st column
i Destroyed
d
e
b4.5Complex number Addition Using Operator Overloading
a
r
#include<iostream.h>
i
class complex
{
s
int a,b;
public:
a complex()
{
s }
t complex(int x,int y)
Self –instructional material a 24
n
d
a
Oops concepts
{
a=x;
[
b=y;
} T Notes
friend complex operator +(complex,complex); y
void display() p
{ e
cout<<"The Complex Number Is...\n";
cout<<a<<"+"<<b<<"j"; t
} h
};
e
complex operator +(complex ob,complex ob1)
{
complex ob2; s
ob2.a=ob.a+ob1.a; i
ob2.b=ob.b+ob1.b; d
return ob2; e
} b
int main() a
{
r
float a1,b1,a2,b2;
cout<<"Enter The Real Part :";
cin>>a1>>a2; c
complex m(a1,a2); o
cout<<"Enter The ImaginoryPart :"; n
cin>>b1>>b2; t
complex(b1,b2); e
complex s; n
s=m+n; t
s.disp();
.
return 0;
}
A
Output :
Enter The Real Part : s
3 2 i
Enter The Imaginary Part : d
3 2 e
The Complex Number Is... b
6 + 4j
a
r
4.6 Write a Program for Factorial Using Recursion
i
s
#include<iostream>
int f(int n)
a
{
if(n<=1)
{ s
return 1; t
25 a
Self –instructional material
n
d
a
Oops concepts
}
else
[ {
Notes T return n*f(n-1);
y }
p}
eint main()
{
t int num;
cout<<"Enter Number :";
h
cin>>num;
e cout<<"Factorial Is ="<<f(num);
return 0;
s}
i
dOutput :
eEnter Number : 4
b Factorial Is =24
a
r
UNIT 5
c
o
Inheritance and Polymorphism:
n Inheritance types and polymorphism,
t
e
Virtual function
n
t5.1 Write a Program for Product Details using Multilevel
. Inheritance

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
.

7.2 Write a Program for Array of Pointers A

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

Enter option->1.push 2.pop 3.display 4.exit:1


s
Enter the element:20
i
Enter option->1.push 2.pop 3.display 4.exit:1 d
Enter the element:30 e
b
Enter option->1.push 2.pop 3.display 4.exit:1 a
Stack is full r
Enter option->1.push 2.pop 3.display 4.exit:3
Elements of the stack are:
c
10
20 o
30 n
Enter option->1.push 2.pop 3.display 4.exit:2 t
30is deleted from the stack e
Enter option->1.push 2.pop 3.display 4.exit:3 n
Elements of the stack are: t
10 .
20

Enter option->1.push 2.pop 3.display 4.exit:4 A

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.

Applications of Queue Data Structure


Breadth First Search property of Queue makes it also useful in
following kind of scenarios.
1. When a resource is shared among multiple consumers.
Examples include CPU scheduling, Disk Scheduling.
2. When data is transferred asynchronously (data not necessarily
received at same rate as sent) between two processes. Examples
include IO Buffers, pipes, file IO, etc.
9.1 Queue Using Array

#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
{

Node* newNode = *sourceRef;


assert(newNode != NULL);
Notes *sourceRef = newNode->next;
newNode->next = *destRef;
*destRef = newNode;
}
void push(Node** head_ref, int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* Function to print nodes in a given linked list */
void printList(Node *node)
{
while (node!=NULL)
{
cout<<node->data<<" ";
node = node->next;
}
}
/* Driver code*/
int main()
{
/* Start with the empty list */
Node* res = NULL;
Node* a = NULL;
Node* b = NULL;
/* Let us create two sorted linked liststo test the functions
Created lists, a: 5->10->15, b: 2->3->20 */
push(&a, 15);
push(&a, 10);
push(&a, 5);
push(&b, 20);
push(&b, 3);
push(&b, 2);
res = SortedMerge(a, b);
cout<< "Merged Linked List is: \n";
printList(res);
return 0;
}

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.

Insertion and Deletion of linked list


In this program, we will learn how to implement Linked List using
C++ program
In this example, we will implement a singly linked list with insert,
delete and display operations. Here, we will declare Linked List Node,
Insert Node at the beginning, Delete Node from beginning and display all
linked list Nodes.

10.3Program ForLinked List Implementation

#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

10.4 Program of Linked Lists Traversal in a list


i
s
#include<iostream.h>
#include<conio.h> a
#include<process.h>
struct node s
{ t
int info; a
n
47 Self –instructional material
d
a
l
Linear data structure
node *next;
} *start, *newptr, *save, *ptr, *rear;
node *create_new_node(int);
void insert_node(node *);
Notes void travers(node *);
void main()
{
clrscr();
start = rear = NULL;
int inf;
char ch='y';
while(ch=='y' || ch=='Y')
{
cout<<"Enter Information for the new node: ";
cin>>inf;
newptr = create_new_node(inf);
if(newptr == NULL)
{
cout<<"\nSorry..!!..cannot create new
node..!!..Aborting..!!";
cout<<"\nPress any key to exit..";
getch();
exit(1);
}
insert_node(newptr);
cout<<"Want to enter more nodes ? (y/n)..";
cin>>ch;
cout<<"\n";
}
cout<<"The list now is:\n";
travers(start);
getch();
}
node *create_new_node(int n)
{
ptr = new node;
ptr->info = n;
ptr->next = NULL;
return ptr;
}
void insert_node(node *np)
{
if(start==NULL)
{
start = rear = np;
}
else
{
rear -> next = np;
rear = np;
}
}

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.

Following are common types of Binary Trees.


Full Binary Tree A Binary Tree is full if every node has 0 or 2
children. Following are examples of a full binary tree. We can also say a
full binary tree is a binary tree in which all nodes except leaves have two
children.

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

Where L = Number of leaf nodes, I = Number of internal nodes

Self –instructional material 50


See Handshaking Lemma and Tree for proof. Non-linear data structure
[
Complete Binary Tree: A Binary Tree is complete Binary Tree if T
all levels are completely filled except possibly the last level and the last y
level has all keys as left as possible p Notes
e

Following are examples of Complete Binary Trees t


h
18
/ \ e
15 30
/ \ / \ s
40 50 100 40 i
d
e
b
a
18
/ \ r
15 30
/ \ /\ c
40 50 100 40 o
/ \ / n
8 79 t
e
Practical example of Complete Binary Tree is Binary Heap.
n
Perfect Binary Tree a Binary tree is Perfect Binary Tree in which
all internal nodes have two children and all leaves are at the same level. t
Following are examples of Perfect Binary Trees. .
18
/ \ A
15 30
/ \ / \ s
40 50 100 40 i
d
e
18
b
/ \
15 30 a
A Perfect Binary Tree of height h (where height is the number of r
nodes on the path from the root to leaf) has 2h – 1 node.
Example of a Perfect binary tree is ancestors in the family. Keep i
a person at root, parents as children, Parents of parents as their children. s

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.

A degenerate (or pathological) tree A Tree where every internal


Notes node has one child. Such trees are performance-wise same as linked list.

10
/
20
\
30
\
40

Representing Binary Tree


in memory
Let T be a Binary Tree. There are two ways of representing T in the
memory as follow

 Sequential
Representation of Binary Tree.
 Link Representation of Binary Tree.

1) Linked Representation of Binary Tree


Consider a Binary Tree T. T will be maintained in memory by
means of a linked list representation which uses three parallel arrays;
INFO, LEFT, and RIGHT pointer variable ROOT as follows. In Binary
Tree each node N of T will correspond to a location k such that

LEFT [k] contains the location of the left child of node N.


INFO [k] contains the data at the node N.
RIGHT [k] contains the location of right child of node N.

Representation of a node:

Node Representation

In this representation of binary tree root will contain the location of


the root R of T. If any one of the sub tree is empty, then the corresponding
pointer will contain the null value if the tree T itself is empty, the ROOT
will contain the null value.

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.

Self –instructional material 52


Non-linear data structure
[
T
y
p Notes
e

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:

Notes Sequential Representation of Binary Tree 1


Traversing Binary Trees
Traversing a tree means visiting every node in the tree. You might for
instance want to add all the values in the tree or find the largest one. For all
these operations, you will need to visit each node of the tree.

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)

Self –instructional material 54


Non-linear data structure
[
T
y
p Notes
e

t
h
e

Binary search tree s


Binary Search Tree is a node-based binary tree data structure
i
which has the following properties:
The left subtree of a node contains only nodes with keys lesser d
than the node’s key. e
The right subtree of a node contains only nodes with keys greater b
than the node’s key. a
The left and right subtree each must also be a binary search tree. r

Insertion in Binary Search Tree: c


Check whether root node is present or not(tree available or not). o
If root is NULL, create root node. n
If the element to be inserted is less than the element present in the t
root node, traverse the left sub-tree recursively until we reach T->left/T-
e
>right is NULL and place the new node at T->left(key in new node < key
in T)/T->right (key in new node > key in T). n
If the element to be inserted is greater than the element present in root t
node, traverse the right sub-tree recursively until we reach T->left/T- .
>right is NULL and place the new node at T->left/T->right.
Deletion in Binary Search Tree: A
How to delete a node from binary search tree?
There are three different cases that needs to be considered for s
deleting a node from binary search tree. i
d
11.1 Program for Insertion, Deletion and Traversal in e
Binary Search Tree b
a
r
#include <stdio.h>
#include <stdlib.h> i
struct treeNode { s
int data;
struct treeNode *left, *right; a
};
struct treeNode *root = NULL;
struct treeNode* createNode(int data) { s
struct treeNode *newNode; t
newNode = (struct treeNode *) malloc(sizeof (struct treeNode)); a
n
55 Self –instructional material
d
a
l
newNode->data = data;
Non-linear data structure newNode->left = NULL;
newNode->right = NULL;
return(newNode);
}
void insertion(struct treeNode **node, int data) {
Notes if (*node == NULL) {
*node = createNode(data);
} else if (data < (*node)->data) {
insertion(&(*node)->left, data);
} else if (data > (*node)->data) {
insertion(&(*node)->right, data);
}
}
void deletion(struct treeNode **node, struct treeNode **parent, int data)
{
struct treeNode *tmpNode, *tmpParent;
if (*node == NULL)
return;
if ((*node)->data == data) {
if (!(*node)->left && !(*node)->right) {
if (parent)
if ((*parent)->left == *node)
(*parent)->left = NULL;
else
(*parent)->right = NULL;
free(*node);
} else {
free(*node);
}
} else if (!(*node)->right && (*node)->left)
tmpNode = *node;
(*parent)->right = (*node)->left;
free(tmpNode);
*node = (*parent)->right;
} else if ((*node)->right && !(*node)->left) {
tmpNode = *node;
(*parent)->left = (*node)->right;
free(tmpNode);
(*node) = (*parent)->left;
} else if (!(*node)->right->left)
tmpNode = *node;
(*node)->right->left = (*node)->left;
(*parent)->left = (*node)->right;
free(tmpNode);
*node = (*parent)->left;
} else {
tmpNode = (*node)->right;
while (tmpNode->left) {
tmpParent = tmpNode;
tmpNode = tmpNode->left;
}

Self –instructional material 56


tmpParent->left = tmpNode->right; Non-linear data structure
tmpNode->left = (*node)->left; [
tmpNode->right =(*node)->right; T
free(*node); y
*node = tmpNode; p Notes
}
e
} else if (data < (*node)->data) {
deletion(&(*node)->left, node, data);
} else if (data > (*node)->data) { t
deletion(&(*node)->right, node, data); h
} e
}
void findElement(struct treeNode *node, int data) { s
if (!node) i
return;
d
else if (data < node->data) {
findElement(node->left, data); e
} else if (data > node->data) { b
findElement(node->right, data); a
} else r
printf("data found: %d\n", node->data);
return; c
o
}
n
void traverse(struct treeNode *node) {
if (node != NULL) { t
traverse(node->left); e
printf("%3d", node->data); n
traverse(node->right); t
} .
return;
} A
int main() {
int data, ch;
s
while (1) {
printf("1. Insertion in Binary Search Tree\n"); i
printf("2. Deletion in Binary Search Tree\n"); d
printf("3. Search Element in Binary Search Tree\n"); e
printf("4. Inorder traversal\n5. Exit\n"); b
printf("Enter your choice:"); a
scanf("%d", &ch); r
switch (ch) {
case 1:
i
while (1) {
printf("Enter your data:"); s
scanf("%d", &data);
insertion(&root, data); a
printf("Continue Insertion(0/1):");
scanf("%d", &ch); s
if (!ch) t
break; a
n
57 Self –instructional material
d
a
l
}
Non-linear data structure break;
case 2:
printf("Enter your data:");
scanf("%d", &data);
deletion(&root, NULL, data);
Notes break;
case 3:
printf("Enter value for data:");
scanf("%d", &data);
findElement(root, data);
break;
case 4:
printf("Inorder Traversal:\n");
traverse(root);
printf("\n");
break;
case 5:
exit(0);
default:
printf("u've entered wrong option\n");
break;
}
}
return 0;
}

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

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:4
Inorder Traversal:
19 20 21 23 25 26 30
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:2
Enter your data:30

Delete node 30

20
/ \
19 25
/ \
21 26
\
23

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:4
Inorder Traversal:
19 20 21 23 25 26
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit

Self –instructional material 60


Enter your choice:2 Non-linear data structure
Enter your data:20 [
T
Delete node 20 y
21 p Notes
/ \
e
19 25
/ \
23 26 t
h
e

1. Insertion in Binary Search Tree s


2. Deletion in Binary Search Tree i
3. Search Element in Binary Search Tree
d
4. Inorder traversal
5. Exit e
Enter your choice:4 b
Inorder Traversal: a
19 21 23 25 26 r
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree c
3. Search Element in Binary Search Tree o
4. Inorder traversal
n
5. Exit
Enter your choice:1 t
Enter your data:15 e
Continue Insertion(0/1):1 n
Enter your data:14 t
Continue Insertion(0/1):1 .
Enter your data:16
Continue Insertion(0/1):1 A
Enter your data:17
Continue Insertion(0/1):0
s
Binary Search Tree After Insertion Operation:
i
21 d
/ \ e
19 25 b
/ / \ a
15 23 26 r
/ \
14 16
i
\
17 s

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
n
61 Self –instructional material
d
a
l
Enter your choice:4
Non-linear data structure Inorder Traversal:
14 15 16 17 19 21 23 25 26
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
Notes 4. Inorder traversal
5. Exit
Enter your choice:2
Enter your data:15
Delete Node 15

21
/ \
19 25
/ / \
16 23 26
/ \
14 17

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:4
Inorder Traversal:
14 16 17 19 21 23 25 26
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:3
Enter value for data:21
data found: 21
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:5

Self –instructional material 62


Non-linear data structure

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;

63 Self –instructional material


Non-linear data structure
}
void dijkstra(int graph[vertex][vertex],int src)
Notes {
int dist[vertex];
bool Dset[vertex];
for(int i=0;i<vertex;i++)
{
dist[i]=INT_MAX;
Dset[i]=false;
}
dist[src]=0;
for(int c=0;c<vertex;c++)
{
int u=minimumDist(dist,Dset);
Dset[u]=true;
for(int v=0;v<vertex;v++)
{
if(!Dset[v] && graph[u][v] &&dist[u]!=INT_MAX
&&
dist[u]+graph[u][v]<dist[v])
dist[v]=dist[u]+graph[u][v];
}
}
cout<<"Vertex\t\tDistance from source"<<endl;
for(int i=0;i<vertex;i++)
{
char c=65+i;
cout<<c<<"\t\t"<<dist[i]<<endl;
}
}
int main()
{
int
graph[vertex][vertex]={{0,5,3,0,0,0,0},{0,0,2,0,3,0,1},{0,0,0,7,7,0,0},{2,0
,0,0,0,6,0},{0,0,0,2,0,1,0},{0,0,0,0,0,0,0}, {0,0,0,0,1,0,0}};
dijkstra(graph,0);
return 0;
}

Output :

Vertex Distance from source


A 0
B 5
C 3
D 9
E 7
F 8
G 6

64
Self –instructional material
Non-linear data structure

Notes
Graphs with Negative Edge costs

C++ Programming examples on “Shortest Path” Bellman–Ford


algorithm is an algorithm that computes shortest paths from a single source
vertex to all of the other vertices in a weighted digraph. Floyd–Warshall
algorithm is an algorithm for finding shortest paths in a weighted graph
with positive or negative edge weights.

12.2 Floyd Warshall Algorithm

#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;

// Relaxation step (run V-1 times)


while (--k)
{
for (int j = 0; j < E; j++)
{
// edge from u to v having weight w
u = edges[j].source, v = edges[j].dest;
w = edges[j].weight;

65 Self –instructional material


Non-linear data structure

if (distance[u] != INT_MAX && distance[u] + w <


Notes distance[v])
{
// update distance to the new lower value
distance[v] = distance[u] + w;

// set v's parent as u


parent[v] = u;
}
}
}
for (int i = 0; i< E; i++)
{
// edge from u to v having weight w
u = edges[i].source, v = edges[i].dest;
w = edges[i].weight;
if (distance[u] != INT_MAX && distance[u] + w <
distance[v])
{
cout<< "Negative Weight Cycle Found!!";
return;
}
}
for (int i = 0; i< N; i++)
{
cout<< "Distance of vertex " <<i<< " from the source is "
<<setw(2) << distance[i] << ". It's path is [ ";
printPath(parent, i); cout<< "]" << '\n';
}
}
// main function
int main()
{
// vector of graph edges as per above diagram
vector<Edge> edges =
{
// (x, y, w) -> edge from x to y having weight w
{ 0, 1, -1 }, { 0, 2, 4 }, { 1, 2, 3 }, { 1, 3, 2 },
{ 1, 4, 2 }, { 3, 2, 5 }, { 3, 1, 1 }, { 4, 3, -3 }
};
// Set maximum number of nodes in the graph
int N = 5;
// let source be vertex 0
int source = 0;
// run Bellman-Ford algorithm from given source
BellmanFord(edges, source, N);
return 0;
}

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;

67 Self –instructional material


Non-linear data structure

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

Runtime Test Cases


Case 1:
Enter the number of edges for the random graphs: 10

The generated random random graph is:


1->{ }
2->{ 8 8 12 }
3->{ 5 14 }
4->{ Isolated Vertex! }
5->{ }
6->{ Isolated Vertex! }
7->{ Isolated Vertex! }
8->{ 17 }
9->{ Isolated Vertex! }
10->{ 5 }
11->{ Isolated Vertex! }
12->{ 5 }
13->{ Isolated Vertex! }
14->{ }
15->{ 1 }
16->{ 3 }
17->{ }
18->{ Isolated Vertex! }
19->{ Isolated Vertex! }
20->{ Isolated Vertex! }

Case 2:
Enter the number of edges for the random graphs: 50

The generated random random graph is:


1->{ 3 }
2->{ 8 8 12 17 12 6 }
3->{ 5 14 14 18 }
4->{ 12 2 }
5->{ 9 15 20 11 13 }
6->{ }
7->{ 6 2 17 }
8->{ 17 7 20 5 }
9->{ 7 }
10->{ 5 13 19 4 2 }
11->{ 3 10 }
12->{ 5 19 9 }
13->{ 3 }
14->{ 5 9 9 16 7 }
15->{ 1 }
16->{ 3 15 }
17->{ 16 1 }

69 Self –instructional material


Non-linear data structure
18->{ 20 }
19->{ 16 3 }
Notes 20->{ }

All pair shortest paths algorithm


The all-pairs shortest path problem is the determination of the
shortest graph distances between every pair of vertices in a given graph. ...
The matrix of all distances between pairs of vertices is called the graph
distance matrix, or sometimes the all-pairs shortest path matrix.

12.4 Program to implement dynamic programming


algorithm to solve the all pairs shortest path problem

#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

Minimum-cost spanning tree.


A Minimum Spanning Tree (MST) works on graphs with directed
and weighted (non-negative costs) edges. Consider a graph G with n
vertices. The spanning tree is a subgraph of graph G with all its n vertices
connected to each other using n-1 edges.

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.

Application of Minimum Spanning Tree


1. Consider n stations are to be linked using a communication network
& laying of communication links between any two stations
involves a cost.

71 Self –instructional material


Non-linear data structure
2. The ideal solution would be to extract a subgraph termed as
minimum cost spanning tree.
Notes 3. Suppose you want to construct highways or railroads spanning
several cities then we can use the concept of minimum spanning
trees.
4. Designing Local Area Networks.
5. Laying pipelines connecting offshore drilling sites, refineries and
consumer markets.
6. Suppose you want to apply a set of houses with
 Electric Power
 Water
 Telephone lines
 Sewage lines
To reduce cost, you can connect houses with minimum cost spanning trees.
12.5 Program for Kruskal's algorithm to find Minimum
Spanning Tree of a given connected ,undirected and
weighted graph

#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;

73 Self –instructional material


Non-linear data structure
Edge result[V]; // Tnis will store the resultant MST
int e = 0;
Notes int i = 0;
qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);
// Allocate memory for creating V ssubsets
subset *subsets = new subset[( V * sizeof(subset) )];
// Create V subsets with single elements
for (int v = 0; v < V; ++v)
{
subsets[v].parent = v;
subsets[v].rank = 0;
}
// Number of edges to be taken is equal to V-1
while (e < V - 1 &&i< graph->E)
{
Edge next_edge = graph->edge[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
if (x != y)
{
result[e++] = next_edge;
Union(subsets, x, y);
}
// Else discard the next_edge
}
// print the contents of result[] to display the
// built MST
cout<<"Following are the edges in the constructed MST\n";
for (i = 0; i< e; ++i)
cout<<result[i].src<<" -- "<<result[i].dest<<" ==
"<<result[i].weight<<endl;
return;
}
// Driver code
int main()
{
int V = 4; // Number of vertices in graph
int E = 5; // Number of edges in graph
Graph* graph = createGraph(V, E);
// add edge 0-1
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = 10;
// add edge 0-2
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 6;
// add edge 0-3
graph->edge[2].src = 0;
graph->edge[2].dest = 3;
graph->edge[2].weight = 5;

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.

The program below implements Prim's algorithm in C++.


Although adjacency matrix representation of graph is used, this algorithm
can also be implemented using Adjacency List to improve its efficiency.
12.6Program for Prim's Algorithm Implementation

#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));

75 Self –instructional material


Non-linear data structure
no_edge = 0;
selected[0] = true;
Notes int x; // row number
int y; // col number
// print for edge and weight
cout<< "Edge" <<" : " << "Weight";
cout<<endl;
while (no_edge< V - 1)
{
int min = INF;
x = 0;
y = 0;
for (int i = 0; i< V; i++) {
if (selected[i]) {
for (int j = 0; j < V; j++) {
if (!selected[j] && G[i][j]) {
if (min > G[i][j]) {
min = G[i][j];
x = i;
y = j;
}

}
}
}
}
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

Breadth First Traversal


Breadth First Search (BFS) algorithm traverses a graph in a
breadthward motion and uses a queue to remember to get the next vertex to
start a search, when a dead end occurs in any iteration.

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

77 Self –instructional material


Non-linear data structure
12
23
Notes 15
14
47
78
89
26
57
Enter initial vertex1
Visited vertices
12 4 5 3 6 7 8 9

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.

13.1 Simple Linear Search Example Program (Sequential


search)

#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;

79 Self –instructional material


for(i=0;i<n;i++)
{
if(y==data[i])
Searching And Sorting
{
Algorithms
f=1;
break;
}
}
if(f==1)
Notes
{
cout<<"\nThe given search element "<<y<<" found at index "
<<i<<endl;
}
else
{
cout<<"\n Element Not found";
}
}

void main()
{
clrscr();
linear ob;
ob.get();
ob.search();
getch();
}

Output
======
Enter n value: 5
Enter the 5 values.... 1 2 3 4 5

Enter the search element: 4


The given search element 4 is found at the index 3

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])
{

81 Self –instructional material


high=mid-1;
}
else
Searching And Sorting
{
Algorithms
low=mid+1;
}
if(a[mid]==x)
{
flag=0;
Notes
break;
}
else
{
flag=1;
}
}
if(flag==0)
{
cout<<"\nThe required Element "<<x<<" is found\n";
}
else
{
cout<<"Element not found";
}
}
void main()
{
clrscr();
cout<<"\t\t\tBINARY SEARCH\n";
binary b;
b.getdata();
b.sorting();
b.searching();
getch();
}

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;

83 Self –instructional material


}
}
cout<<"\nAfter"<<i<<"iteration\n";
Searching And Sorting
for(k=0;k<n;k++)
Algorithms
{
cout<<data[k]<<"\t";
}
}
}
Notes
void bubble::display()
{
cout<<"\nAfter sorting\n";
for (i=0;i<n;i++)
{
cout<<data[i]<<"\t";
}
}
void main()
{
clrscr();
cout<<"\t\t\tBUBBLE SORT\n";
bubble i;
i.getdata();
i.calculation();
i.display();
getch();
}

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.

14.2Program for Quick Sort

#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;

85 Self –instructional material


low=lb+1;
high=mb;
pivot=data[lb];
Searching And Sorting
while(flag)
Algorithms
{
while(data[low]<pivot && low<mb)
{
low++;
}
Notes
while(data[high]>pivot)
{
high--;
}
if(low<high)
{
t=data[low];
data[low]=data[high];
data[high]=t;
}
else
flag=0;
}
t=data[lb];
data[lb]=data[high];
data[high]=t;
cout<<"\nAfter "<<l<<" iteration....\n";
l++;
for(int i=0;i<n;i++)
{
cout<<data[i]<<"\t";
}
cout<<endl;
quicksort(data,lb,high-1);
quicksort(data,high+1,mb);
}
}

/*OUTPUT
QUICK SORT
Enter n value: 5

Enter the 5 elements


12 65 3 6 18

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:

14.3 Programming Code for Insertion Sort

#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++)

87 Self –instructional material


{
t=data[i];
for(j=i;j>0 && t<data[j-1];j--)
Searching And Sorting
{
Algorithms
data[j]=data[j-1];
}
cout<<"\n\nAfter "<<i<<" iteration\n\n";
for(int k=0;k<n;k++)
{
Notes
cout<<data[k]<<"\t";
}
data[j]=t;
}
}
void sort::display()
{
cout<<"\n\nAfter sorting....\n\n";
for(i=0;i<n;i++)
{
cout<<data[i]<<endl;
}
}
void main()
{
clrscr();
cout<<”Insertion Sort \n”;
sort ob;
ob.get();
ob.sort();
ob.display();
getch();
}

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

14.4Program For Merge Sort

#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++;

89 Self –instructional material


}
}
for(k=low;k<=high;k++)
Searching And Sorting
{
Algorithms
data[k]=b[k];
}
cout<<endl;

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

91 Self –instructional material

You might also like