Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

COMPUTER LABORATORY MANUAL

CS-250
Data Structures and Algorithms

DEPARTMENT OF COMPUTER SOFTWARE ENGINEERING


Military College of Signals
National University of Sciences and Technology
www.mcs.nust.edu.pk
PREFACE
This lab manual has been prepared to facilitate the students of software engineering in studying and analyzing data
structures and algorithms. The aim of this course is to provide an introduction to computer algorithms and data structures,
with an emphasis on practical implementations. Data Structures and Algorithms introduces fundamental techniques for
problem solving that are relevant to most areas of computer science, both theoretical and applied. Algorithms and data
structures for sorting, searching, graph problems, and geometric problems are covered. The lab manual is designed to help
students understand the basic concepts of data structures and implement basic computer science algorithms in object-
oriented approach.

PREPARED BY
Lab manual is prepared by Dr. Naima Iltaf and Lab Engr. Misbah Ghalib under the supervision of Head of Department Dr.
Naveed Iqbal Rao in year 2014.

GENERAL INSTRUCTIONS
a. Students are required to maintain the lab manual with them till the end of the semester.
b. All readings, answers to questions and illustrations must be solved on the place provided. If more space is
required then additional sheets may be attached.
c. It is the responsibility of the student to have the manual graded before deadlines as given by the instructor
d. Loss of manual will result in re submission of the complete manual.
e. Students are required to go through the experiment before coming to the lab session. Lab session details will
be given in training schedule.
f. Students must bring the manual in each lab.
g. Keep the manual neat clean and presentable.
h. Plagiarism is strictly forbidden. No credit will be given if a lab session is plagiarized and no re submission
will be entertained.
i. Marks will be deducted for late submission
VERSION HISTORY

Date Updated By Details

Sept 2012 Asst Prof Bilal Rauf First Version Created


Aug 2014 Dr Naima Iltaf Updated Experiment 1 and Experiment 3
Added resources and summaries to the experiments. Formatted the
Jan 2016 Aamna Mehfooz
manual according to standard. New exercises have been added
A/P Bilal Rauf & Lab Engr.
Sept 2017 Added new lab and contents revised.
Maemoona Kayani
A/P Bilal Rauf & Lab Engr.
Oct 2018 Added Lab Rubrics
Maemoona Kayani
A/p Dr Zaki, Lab Engr Marium
Sept 2019 Updated CLOs and exercises
Hida
Lt Col Khawir Mehmood, Lab
Oct 2021 New Lab added, Lab Rubrics and Course CLOs updated
Engr Marium Hida

2 Data Structures and Algorithms


Mapping of Lab Experiments

Lab Rubrics (Group 1)

Criteria Unacceptable Substandard Adequate Proficient


(Marks=0) Marks=1 Marks=2 Marks=3

The program execution


let to inaccurate or
R1 The program was The program was
The program failed incomplete results. It
Completeness correctly functional and correctly functional,
to produce the right was not correctly
most of the features and all the features
And Accuracy accurate result functional or not all the
were implemented were implemented
features were
implemented

The student fails to Student successfully Student successfully Student successfully


R2 figure out the syntax figures out few of syntax figures out most of figures out all syntax
Syntax and and semantic errors and semantic errors of syntax and semantic and semantic errors
Semantics of the incorrect the program with errors of the program of the program
program extensive guidance with minimum guidance without any guidance

Student has
demonstrated on
Student has basic accurate
Student failed to Student has basic
R3 knowledge of understanding of the
demonstrate a clear understanding, but asked
understanding. Provides lab objective and
Demonstration understanding of questions were not
fundamental answers to concepts. All the
the assigned task answered.
asked questions questions are
answered completely
and correctly

R4 The code is readable only The code is


The code is poorly
by someone who knows The code is fairly easy to exceptionally well
Complexity and organized and very
what it is supposed be read organized and very
Readability difficult to read
doing easy to follow

Complete working
program is copied
R5 Most of working program Most of working Complete working
indicating no effort
is copied. Minor program is contributed program is
Perseverance on student’s part
contribution by the by the student. Minor contributed by the
and plagiarism resulting in a total
student copied components student
score of zero for all
rubrics

3 Data Structures and Algorithms


Lab Rubrics (Group 3)

Criteria Unacceptable Substandard Adequate Proficient


(Marks=0) Marks=1 Marks=2 Marks=3

The system execution let


to inaccurate or
The system was The system was
R1 The system failed to incomplete results. It
correctly functional and correctly functional,
Completeness produce the right was not correctly
most of the features and all the features
and Accuracy accurate result functional or not all the
were implemented were implemented
features were
implemented

The student has


demonstrated on
The student has basic The student has accurate
The student failed to
R2 knowledge of moderate knowledge of understanding of the
demonstrate a clear
understanding but asked understanding. Answer lab objective and
Demonstration understanding of the
questions were not to the question are concepts. All the
assigned task
answered. basic questions are
answered completely
and correctly

Complete working
program is copied
Most of working Most of working Complete working
R3 indicating no effort
program is copied. program is contributed program is
on student’s part
Plagiarism Minor contribution by by the student. Minor contributed by the
resulting in a total
the student copied components student
score of zero for all
rubrics

R4 Shows little Demonstrates Demonstrates Actively helps to


commitment to commitment to group commitment to group identify group goals
Contribution/ group goals and fails goals, but has difficulty goals and carries out and works effectively
Group to perform assigned performing assigned assigned roles to meet them in all
participation roles roles effectively roles assumed

Poor presentation;
Well-organized, clear
cannot explain topic; Presentation lacks clarity Presentation
R5 presentation; good
scientific and organization; little acceptable; adequate
use of scientific
Presentation terminology lacking use of scientific terms use of scientific terms;
vocabulary and
skills or confused; lacks and vocabulary; poor acceptable
terminology; good
understanding of understanding of topic understanding of topic
understanding of topic
topic

4 Data Structures and Algorithms


COURSE LEVEL OUTCOMES
CS-250 Data Structures and Algorithm

Course Learning Outcomes (CLOs)

At the end of the course the students will be able to: PLOs BT Level*

1. Discuss various data structures and their algorithms 1 C-2


2. Apply simple algorithms and determine their complexities 2 C-3
3 Apply appropriate data structures and algorithms 3 C-3
4 Practice and apply appropriate data structures and algorithms 5 P-3
to design solutions

S No List of Experiments CLO R-G


1 C++ Pointers and Arrays 4 1
2 Singly Linked List 4 1
3 Doubly Linked List 4 1
4 Stacks Static and Dynamic Implementation 4 1
5 Applications of Stack 4 1
6 Queues Static and Dynamic Implementation 4 1
7 Recursion 4 1
7b Tower of Hanoi 4 1
8 Sorting 4 1
9 Searching-Linear and Binary 4 1
10 Binary Search Tree 4 1
11 Graph 4 1
12 Graph-Mst and Djikstra Algo 4 1
13 Hashing 4 1
14 Huffman Coding Compression Algorithm 4 1
15 Lab Exam 4 1
16 Project 4 3

5 Data Structures and Algorithms


MARKS

Instructor
Max. Marks Obtained
Date Experiment Sign
Marks
R1 R2 R3 R4 R5

Grand Total

6 Data Structures and Algorithms


LIST OF EXPERIMENTS
EXPERIMENT 1 – REVISION OF C++ POINTERS AND ARRAYS .................................................................................8
EXPERIMENT 2 – SINGLY LINKED LISTS .....................................................................................................................18
EXPERIMENT 3 – DOUBLY LINKED LISTS .................................................................................................................27
EXPERIMENT 4 – STACKS – DYNAMIC AND STATIC IMPLEMENTATION ........................................................... 31
EXPERIMENT 5 – APPLICATIONS OF STACK .............................................................................................................. 36
EXPERIMENT 6 – QUEUES – DYNAMIC IMPLEMENTATION ................................................................................... 39
EXPERIMENT 7a – RECURSION ...................................................................................................................................... 44
EXPERIMENT 7b – TOWER OF HANOI ........................................................................................................................ 47
EXPERIMENT 8 – SORTING ............................................................................................................................................. 49
EXPERIMENT 9 – SEARCHING-LINEAR AND BINARY .............................................................................................. 53
EXPERIMENT 10 – BINARY SEARCH TREE ..................................................................................................................56
EXPERIMENT 11 – GRAPH ............................................................................................................................................... 58
EXPERIMENT 12 – GRAPH- MST & DIJKSTRA ALGO ............................................................................................. 61
EXPERIMENT 13 – HASHING ...........................................................................................................................................64
EXPERIMENT 14 – HUFFMAN CODING COMPRESSION ALGORITHM ............................................................. 66

7 Data Structures and Algorithms


EXPERIMENT 1 – REVISION OF C++ POINTERS AND ARRAYS
1. Objectives:
(a). Revise arrays and use of arrays with pointers
(b). To learn basic terminologies and syntax to use pointers in C++
2. Time Required: 3 hrs
3. Software Required:
(a). Windows OS
(b). Bloodshed Dev C++
(c). Microsoft Visual Studio 2012

4. Constructors:
It is convenient if an object can initialize itself when it is first created, without need to make a
separate call to its member functions. C++ provides a non-static member function called as
constructor that is automatically called when object is created. After objects are created, their
members can be initialized by using constructors.

Important points to be noted while using constructors


 Constructor name must be the same as that of its class name in which it belongs.
 Constructors are invoked automatically when objects are created.
 Constructors cannot specify return types nor return values.
 Constructors cannot be declared static or const.
 Constructors should have public access within the class

The syntax of Constructors is as follows:

<class-name> (list-of-parameters);

Constructors can be defined inside or outside the class declaration:-

The syntax for defining the constructor within the class:

<class-name> (list-of-parameters) { // constructor definition }

The syntax for defining the constructor outside the class:

<class-name>: :<class-name> (list-of-parameters){ // constructor definition

8 Data Structures and Algorithms


Activity 1.1 : Class with Constructor

# include<iostream.h>
class maths{
int a;
public:
maths();
void showdata();
};
maths :: maths(){
cout<<”\n this is a constructor”;
a=100;
}

void maths :: showdata(){


cout<<”\n the value of a=”<<a;
}
void main (){
maths m;
m.showdata();
}

// defining the constructor within the class

#include <iostream>
using namespace std;

class student {
int rno;
char name[10];
double fee;

public:
student()
{
cout << "Enter the RollNo:";
cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
}

void display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
};

int main()
{
student s; // constructor gets called automatically when
// we create the object of the class
s.display();

return 0;
}

9 Data Structures and Algorithms


// defining the constructor outside the class

#include <iostream>
using namespace std;
class student {
int rno;
char name[50];
double fee;

public:
student();
void display();
};

student::student()
{
cout << "Enter the RollNo:";
cin >> rno;

cout << "Enter the Name:";


cin >> name;

cout << "Enter the Fee:";


cin >> fee;
}

void student::display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}

int main()
{
student s;
s.display();

return 0;
}

10 Data Structures and Algorithms


//parameterized constructor

#include <iostream>

using namespace std;


class Line {
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor

private:
double length;
};

// Member functions definitions including constructor


Line::Line( double len) {
cout << "Object is being created, length = " << len <<
endl;
length = len;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}

// Main function for the program


int main() {
Line obj(10.0);

// get initially set length.


cout << "Length of line : " << obj.getLength() <<endl;

// set line length again


obj.setLength(6.0);
cout << "Length of line : " << obj.getLength() <<endl;

return 0;
}

11 Data Structures and Algorithms


5. Destructors:
A destructor is a member function that is called automatically when an object is destroyed.
The syntax for defining the destructor within the class
~ <class-name>()
{
}
Where the class name is the name of the destructor and is preceded by a tilde (~)
(pronounced as til-duh) symbol.
The syntax for defining the destructor outside the class

<class-name>: : ~ <class-name>()
{

It is not possible to define more than one destructor. The destructor is only one way to destroy the
object created by the constructor. Hence destructor can-not be overloaded. Destructor neither
requires any argument nor returns any value. It is automatically called when the object goes out of
scope. Destructors release memory space occupied by the objects created by the constructor. In
destructor, objects are destroyed in the reverse of object creation.

First Example
#include <iostream>
using namespace std;

class Test {
public:
Test() { cout << "\n Constructor executed"; }

~Test() { cout << "\n Destructor executed"; }


};
main()
{
Test t;

return 0;
}
Second Example
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "\n Constructor executed"; }

~Test() { cout << "\n Destructor executed"; }


};

main()
{
Test t, t1, t2, t3;
return 0;
}

12 Data Structures and Algorithms


Characteristics of a destructor:-
1. Destructor is invoked automatically by the compiler when its corresponding constructor
goes out of scope and releases the memory space that is no longer required by the
program.
2. Destructor neither requires any argument nor returns any value therefore it cannot be
overloaded.
3. Destructor cannot be declared as static and const;
4. Destructor should be declared in the public section of the program.
5. Destructor is called in the reverse order of its constructor invocation.

6. Arrays:
An array is a collection of individual values, all of the same data type, stored in adjacent memory
locations. Using the array name together with an integral valued index in square brackets refers to
the individual values. Multi-dimensional arrays have additional indices for each additional
dimension. The index indicates the position of the individual component value within the
collection of values. The index is also called the subscript.
In C++, the first array element always has subscript 0. The second array element has subscript 1,
etc. The base address of an array is its beginning address in memory.

Activity 1.2 : Swap 1st & last element of 1-dimensional Array


#include<iostream.h>
#include<conio.h>

int main()
{
intArr[100],n,temp;
cout<<"Enter number of elements you want to insert ";
cin>>n;

for(inti=0;i<n;i++)
{
cout<<"Enter element "<<i+1<<":";
cin>>Arr[i];
}

temp=Arr[0];
Arr[0]=Arr[n-1];
Arr[n-1]=temp;

cout<<"\nArray after swapping"<<endl;

for(i=0;i<n;i++)
cout<<Arr[i]<<" ";

getch();
return 0;
}

13 Data Structures and Algorithms


7. Pointers:
A pointer is a memory variable that stores a memory address of another variable and can also be
defined as it is a variable that holds the address of some other memory location. It is always
denoted by ‘*’. Following example describes that how to declare and assign memory address to an
integer pointer.

Activity 1.3 : How to use pointer


#include <iostream>
#include<conio.h>
using namespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
cout<< "first value before pointers is "<<firstvalue<<endl;
cout<< "second value before pointers is "<<secondvalue<<endl;
int * p2; //pointers
int *p1 = &firstvalue; // p1 = address of first value
p2 = &secondvalue; // p2 = address of second value
*p1 = 10; // value pointed by p1 = 10
*p2 = 20; // value pointed by p2 = 20
cout<<"After pointers"<<endl;
cout<< "firstvalue is " <<firstvalue<<endl;
cout<< "secondvalue is " <<secondvalue<<endl;
return 0;
}

14 Data Structures and Algorithms


15 Data Structures and Algorithms
8. Exercises:

Exercise 1.1:
Write a program with constructor function and another for destruction function.

Exercise 1.2:
Write a program to search an element (given by user) in a two dimensional array.

16 Data Structures and Algorithms


Exercise 1.3: (4)
Introduce int variables x, y, z and int* pointer variables p, q, r. Set x, y, z to three distinct values.
Set p, q, r to the addresses of x, y, z respectively.

• Print with labels the values of x, y, z, p, q, r, *p, *q, *r.


• Print the message: Swapping values.
• Execute the swap code: z = x; x = y; y = z;
• Print with labels the values of x, y, z, p, q, r, *p, *q, *r.

9. Web Resources:
http://www.tutorialspoint.com/cplusplus/cpp_constructor_destructor.htm
http://www.cplusplus.com/doc/tutorial/arrays/
http://www.tutorialspoint.com/cplusplus/cpp_pointers.htm

10. Video Resources:


http://www.infiniteskills.com/training/programming-c++-training-video/arrays-in-functions.html
http://www.learnerstv.com/video/Free-video-Lecture-5620-Computer-Science.htm
http://www.learnerstv.com/video/Free-video-Lecture-13737-Computer-Science.htm

11. Summary:
This lab session introduces the concepts of constructors and destructors, arrays and pointers in
C++. This lab is designed to revise the concepts of arrays and pointers which will be used in
implementing the concepts of data structures.

17 Data Structures and Algorithms


EXPERIMENT 2 – SINGLY LINKED LISTS
1. Objectives:
(a). Understand the concepts of singly linked lists
(b). Implement singly linked list using dynamic structures
2. Time Required: 3 hrs
3. Software Required:
(a) Microsoft Windows
(b) Microsoft Visual Studio 2012

4. Linked Lists: A linked list is a data structure consisting of a group of nodes which together
represent a sequence. Under the simplest form, each node is composed of a datum and a reference
(in other words, a link) to the next node in the sequence; more complex variants add additional
links. This structure allows for efficient insertion or removal of elements from any position in the
sequence.
last
first

Why Linked List?


Arrays can be used to store linear data of similar types, but arrays have the following
limitations:
 The size of the arrays is fixed: So we must know the upper limit on the number of
elements in advance. Also, generally, the allocated memory is equal to the upper limit
irrespective of the usage.
 Insertion of a new element / Deletion of an existing element in an array of elements is
expensive: The room has to be created for the new elements and to create room existing
elements have to be shifted but in Linked list if we have the head node then we can
traverse to any node through it and insert new node at the required position.

Syntax to create a linked list.


class Node {
public:
int data;
Node* next; //pointer
};
Construction of a simple linked list with 3 nodes:
#include<iostream>
using namespace std;

class Node {
public:
int data;
Node* next; //pointer
};

18 Data Structures and Algorithms


int main()
{
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;

// allocate 3 nodes in the heap


head = new Node();
second = new Node();
third = new Node();

/* Three blocks have been allocated dynamically.


We have pointers to these three blocks as head,
second and third
head second third
| | |
| | |
+---+-----+ +----+----+ +----+----+
| # | # | | # | # | | # | # |
+---+-----+ +----+----+ +----+----+

# represents any random value.


Data is random because we haven’t assigned
anything yet */

head->data = 1; // assign data in first node


head->next = second; // Link first node with
// the second node

/* data has been assigned to the data part of first


block (block pointed by the head). And next
pointer of the first block points to second.
So they both are linked.

head second third


| | |
| | |
+---+---+ +----+----+ +-----+----+
| 1 | o----->| # | # | | # | # |
+---+---+ +----+----+ +-----+----+
*/

// assign data to second node


second->data = 2;

// Link second node with the third node


second->next = third;

/* data has been assigned to the data part of the second


block (block pointed by second). And next
pointer of the second block points to the third
block. So all three blocks are linked.

19 Data Structures and Algorithms


head second third
| | |
| | |
+---+---+ +---+---+ +----+----+
| 1 | o----->| 2 | o-----> | # | # |
+---+---+ +---+---+ +----+----+ */

third->data = 3; // assign data to third node


third->next = NULL;

/* data has been assigned to the data part of the third


block (block pointed by third). And next pointer
of the third block is made NULL to indicate
that the linked list is terminated here.

We have the linked list ready.

head
|
|
+---+---+ +---+---+ +----+------+
| 1 | o----->| 2 | o-----> | 3 | NULL |
+---+---+ +---+---+ +----+------+

Note that only the head is sufficient to represent


the whole list. We can traverse the complete
list by following the next pointers. */

return 0;
}

Traversal of a Linked List


#include<iostream>
using namespace std;

class Node {
public:
int data;
Node* next;
};

// This function prints contents of linked list


// starting from the given node
void printList(Node* n)
{
while (n != NULL) {
cout << n->data << " ";
n = n->next;
}
}

int main()
{
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;

20 Data Structures and Algorithms


// allocate 3 nodes in the heap
head = new Node();
second = new Node();
third = new Node();

head->data = 1; // assign data in first node


head->next = second; // Link first node with second

second->data = 2; // assign data to second node


second->next = third;

third->data = 3; // assign data to third node


third->next = NULL;

// Function call
printList(head);

return 0;
}

5.
Insertion: To insert data in a linked list, a record is created holding the new item. The nextpointer
of the new record is set to link it to the item which is to follow it in the list. The nextpointer of the
item which is to precede it must be modified to point to the new item.

21 Data Structures and Algorithms


A node can be added in three ways
 At the front of the linked list
 After a given node.
 At the end of the linked list.

At the front of the linked list


void front(int n)
{
node *tmp = new node;
tmp -> data = n;
tmp -> next = head;
head = tmp;
}
After a given node
void after(node *a, int value)
{
node* p = new node;
p->data = value;
/*
if initial linked list is
_______ _______ _______
| 1 |____\ | 3 |____\ | 5 |____\ NULL
|_______| / |_______| / |_______| /
and new node's value is 10
then the next line will do something like
_______ _______ _______
| 1 |____\ | 3 |____\ | 5 |____\ NULL
|_______| / |_______| / |_______| /
/ \
|
|
___|___
| 10 |
|_______|
*/
p->next = a->next;
a->next = p;
/*
now the linked list will look like:
_______ _______ _______ _______
| 1 |____\| 10 |____\ | 3 |____\ | 5 |____\ NULL
|_______| /|_______| / |_______| / |_______| /
*/
}

22 Data Structures and Algorithms


At the end of the linked list
void add_node(int n)
{
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;

if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}

6. Deletion:To deleted data from list, The nextpointer of the item immediately preceding the one to
be deleted is altered, and made to point to the item following the deleted item.

23 Data Structures and Algorithms


7. Exercises:

24 Data Structures and Algorithms


Exercise 2.1: (3)

Write a program to display string using linked list. Take a string of character from user and
split the string in character, and then insert each character into linked list.
Example:
String = “RPI”

head R P I NULL

Exercise 2.2:

Consider a scenario where a firm wants to maintain the data of its employees. The data
containing employee number, name, and salary and department # are saved in a singly linked
list. Create following functions for the employee list.
InsertAtFront: Insertion of a record at the front.
InsertAtEnd: Insertion of a record at the end.
Insert: Insertion of a record at any position in the list
DeleteFirst: Deletion of first record.
DeleteLast: Deletion of last record.
Delete: Deletion of a record at any position in the list.
Search: Searching any record based on employee number and dept no.
Display: Displaying all records.

25 Data Structures and Algorithms


Exercise 2.3:

Write a program to split a single linked list in two separate lists and display the both lists.

8. Web Resources:
http://www.cprogramming.com/tutorial/lesson15.html
http://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html
http://www.sourcetricks.com/2008/07/c-singly-linked-lists.html

9. Video Resources:
http://www.youtube.com/watch?v=pBrz9HmjFOs
http://www.youtube.com/watch?v=o5wJkJJpKtM

10. Summary:
This lab session introduces the concepts of single linked lists. It also helps students in
implementing singly linked lists using dynamic allocation.

26 Data Structures and Algorithms


EXPERIMENT 3 – DOUBLY LINKED LISTS
1 Objectives:
. (a). Understanding the concepts and operations of doubly linked lists
(b). Implement doubly linked list using dynamic structures
2 Time Required: 3 hrs
.
3 Software Required:
. (a). Windows OS
(b). Microsoft Visual Studio 2012

4 Doubly Linked Lists:A doubly linked list is a data structure consisting of a group of nodes which
. together represent a sequence and are connected to each other in both directions (Bi-directional). In
Doubly linked list, each node has two pointers. One pointer to its successor (NULL if there is none) and
one pointer to its predecessor (NULL if there is none) which enables bi-directional
traversing.

Head

5 Insertion:To insert data in a doubly linked list, a record is created holding the new item. The next
. pointer of the new record is set to link it to the item which is to follow it in the list. The pre-pointer of the
new record is set to link it to the item which is to before it in the list.

6 Deletion: In deletion process, element can be deleted from three different places. When the node is
. deleted, the memory allocated to that node is released and the previous and next nodes of that node are
linked.

27 Data Structures and Algorithms


7 Exercises:
.
Exercise3.1:

Write a menu driven program to perform insertion, deletion and display functions for doubly linked
list.

28 Data Structures and Algorithms


Exercise 3.2:

Using the Exercise 5.1, write a function MoveToFront( ) with one argument of data type
integer. This function will first search the linked list and compare the Data member of the
node with the given number as argument. If the search finds the number in the list then this
function will move that node to the start of the list as shown in the example below. The order
of the remaining nodes is to remain unchanged. If no node in the list contains the integer,
MoveToFront( ) should leave the list unchanged. Assume that the list contains no duplicate
values. The structure definition of the doubly linked list is

structListNode{
ListNode *pre;
int Data;
ListNode *Next;
}*head;
The function declaration of MoveToFront function is Void MoveToFront(int);

Example:
The two diagrams below illustrate the effect of the call MoveToFront( 5).
Before the call:

29 Data Structures and Algorithms


8 Web References:
. http://idlebrains.org/tutorials/data-structures-tutorials/doubly-linked-list-tutorial/
http://www.codeproject.com/Articles/668818/Implementing-a-Doubly-Linked-List-to-be-used-on-an

9 Video Resource:
. http://www.youtube.com/watch?v=5s0x8bc9DvQ
http://www.youtube.com/watch?v=JdQeNxWCguQ

30 Data Structures and Algorithms


EXPERIMENT 4 – STACKS – DYNAMIC AND STATIC IMPLEMENTATION
1. Objectives:
(a). Understand the concept of stacks and their uses
(b). Implement stacks using both static and dynamic implementation
2. Time Required: 3 hrs
3. Software Required:
(a). Windows OS
(b). Microsoft Visual Studio

4. Stack:
Stack is a memory portion, which is used for storing the elements. The elements are stored based
on the principle of LIFO (Last In, First Out). In stack insertion and deletion of elements take place
at the same end (Top). The last element inserted will be the first to be retrieved.
• This end is called Top
• The other end is called Bottom

Data4 Top

Data3

Data2

Data1 Bottom

5. Top:The stack top operation gets the data from the top-most position and returns it to the user
without deleting it. The underflow state can also occur in stack top operation if stack is empty.

6. Push:The push operation adds a new element to the top of the stack, or initializes the stack if it is
empty. If the stack is full and does not contain enough space to accept the given item, the stack is
then considered to be in an overflow state.
7. Pop:The pop operation removes an item from the top of the stack. A pop either returns previously
inserted items, or NULL if stack is empty.

8. Underflow:When stack contains equal number of elements as per its capacity and no more
elements can be added, the status of stack is known as overflow.

31 Data Structures and Algorithms


9. Dynamic Stack Implementation:

a) Stack Class definition: This class contains private data members i.e. a structure of node
describe the type data to be stored in element and a top pointer to node.

class ListStack{
private:
struct node
{
intnum;
node *next;
}*top;
public:
ListStack()
{
top=NULL;
}
void push();
void pop();
void display();
};

b) Push( ) function:This function creates a new node and ask the user to enter the data to be
saved on the newly created node.

void ListStack::push()
{
node *newNode;
newNode= new node;
cout<<“Enter number to add on stack";
cin>>newNode->num;
newNode->next=top;
top=newNode;
}

32 Data Structures and Algorithms


c) Pop ( ) function: This function deletes an element from top of stack.

void ListStack::pop()
{
node *temp;
temp=top;
if(top==NULL)
cout<<"Stack UnderFlow"<<endl;
else
{
cout<<"deleted Number from the stack =";
cout<<top->num;
top=top->next;
delete temp;
}
}

d) Main( ) function:

33 Data Structures and Algorithms


10. Exercises:

Exercise 4.1: Display ( ) Function test in main function

Write this function to display the elements of stack e.g.


Void ListStack::display()

Exercise 4.2: Implement using static stacks.


Write a program using stack operations, which accepts a non-negative base 10 integer as a parameter,
and display binary representation of number.

Description: To convert a number from decimal to binary, you simply divide by two and push
reminder to stack until quotient is reached to zero, then use pop operation to display the binary
representation of number. For example, to convert (35)10 to binary, you perform the following
computation.

35/2 = 1

17/2 = 1

8/2 = 0

4/2 = 0

2/2 = 0

If you examine the remainders from the last division to the first one, writing them down as you go, you
will get the following sequence: 100011. i.e. (100011)2=(35)10

34 Data Structures and Algorithms


Exercise 4.3:

Write a program to compare opening and closing brackets in expression. This program takes an
expression in the form of string and scan it character by character. Finally the output of the program is
the valid or invalid expression.

Algorithm: To do this comparison a stack ADT can be used to keep track of the scope delimiters
encountered while scanning the expression.

• Whenever a scope “opener” is encountered, it can be “pushed” onto a stack


• Whenever a scope “ender” is encountered, the stack is examined:
– If the stack is “empty”, there is no matching scope “opener” and the expression is invalid.
– If the stack is not empty, we pop the stack and check if the “popped” item corresponds to
the scope ender
– If match occurs, we continue scanning the expression
• When end of the expression string is reached, the stack must be empty, otherwise one or more
opened scopes have not been closed and the expression is invalid

11. Web Resources:


http://www.cs.utsa.edu/~wagner/CS2213/stack/stack.html
http://scanftree.com/Data_Structure/DynamicStack
https://www.cs.bu.edu/teaching/c/stack/array/

12. Video Resources:


http://www.youtube.com/watch?v=sFVxsglODoo
http://www.youtube.com/watch?v=FNZ5o9S9prU

13. Summary:
This lab introduces the concepts of stacks. This lab is designed to implement the concepts of
stacks using both static and dynamic implementation.

35 Data Structures and Algorithms


EXPERIMENT 5 – APPLICATIONS OF STACK
Objectives:
(c). Understand the applications of stacks
(d). Implement stacks using both static and dynamic implementation
Time Required: 3 hrs
Software Required:
(c). Windows OS
(d). Microsoft Visual Studio
4. Infix to Postfix:
An algorithm for parsing an infix notation without parentheses is given here.
Algorithm:
1. Create an empty stack called opstack for keeping operators. Create an empty string for output.
2. Each character in string is a token.
3. Scan the token list from left to right.
o If the token is an operand, append it to the end of the output string.
o If the token is a left parenthesis, push it on the opstack.
o If the token is a right parenthesis, pop the opstack until the corresponding left parenthesis
is removed. Append each operator to the end of the output string.
o If the token is an operator, *, /, +, or -, push it on the opstack. However, first remove any
operators already on the opstack that have higher or equal precedence and append them to
the output list.
4. When the input expression has been completely processed, check the opstack. Any operators still
on the stack can be removed and appended to the end of the output string.

Exercise 5.1:

In this Exercise, you have to take a string expression as input from user. Using this infix expression,
you have to convert it into its equivalent postfix notation.
Example: a + ( b * c )
Read an Expression Stack Output

a a

+ + a

( +( a

b +( ab

* +(* ab

c +(* abc

) + abc*

abc*+

36 Data Structures and Algorithms


5. Parsing Infix Notation: An algorithm for parsing an infix notation without parentheses is given here.

Two stacks are required, one for numbers and the other for operators. The algorithm is:
 For each item in the infix expression (no parentheses) from the right to the left
o If the item is a number then push it on the number stack.
o If the item is an operator (+,-,*, or /) and: the operator stack is empty or the operator on
the top of the stack is higher in priority (* and / are higher in priority than + or -), then
 Pop an operator from the operator stack.
 Pop two numbers off the number stack.
 Calculate using second number-operator-first number.
 Push the result on the number stack.
 Push the item on the operator stack.
o Else push the item on the operator stack.
 After the loop, while the operator stack is not empty
o Pop an operator from the operator stack.
o Pop two numbers off the number stack.
o Calculate using second number-operator-first number.
o Push the result on the number stack.
The answer is the last item in the number stack.

Exercise 5.2:

Write a C++ code to evaluate the infix expression without parenthesis given by user.
Example: 3+4-5/2
Infix String Operand Stack Operator Stack Value
3 3
+ 3 +
4 34 +
- 34 +-
5 345 +-
/ 345 +-/
2 3452 +-/
34 +- / 2 5 -> 5/2 , Push 2
342 +-
3 + - 2 4 -> 4-2, Push 2
32 +
5 + 2 3 -> 3+2, Push 5

37 Data Structures and Algorithms


11. Web Resources:
http://jcsites.juniata.edu/faculty/kruse/cs240/stackapps.html
http://scanftree.com/Data_Structure/Application-of-stack

12. Video Resources:


http://www.youtube.com/watch?v=x_B_mH5BpiE
http://www.youtube.com/watch?v=iWnPbPUfhCg

13. Summary:
This lab introduces different real world applications of stacks and their implementation using
static stacks in C++.

38 Data Structures and Algorithms


EXPERIMENT 6 – QUEUES – DYNAMIC IMPLEMENTATION
1. Objectives:
(a). To understand and implement the concepts of queues using data structures
(b). To learn priority queue and its implementation
2. Time Required: 3 hrs
3. Software Required:
(a). Microsoft Windows
(b). Microsoft Visual Studio 2012

4. Queue:
A queue is a particular kind of collection in which the entities in the collection are kept in order
and the principal (or only) operations on the collection are the addition of entities to the rear
terminal position and removal of entities from the front terminal position. This makes the queue a
First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the
queue will be the first one to be removed. This is equivalent to the requirement that once an
element is added, all elements that were added before have to be removed before the new element
can be invoked. A queue is an example of a linear data structure.

Static: Queue is implemented by an array, and size of queue remains fix

Dynamic: A queue can be implemented as a linked list, and expand or shrink with each enqueue
or dequeue operation.
Front Back

Data1 Data2 Data3 Data4

5. Enqueue:TheEnqueue ( ) operation adds a new item to the end of the queue, or initializes the
queue if it is empty.

6. Dequeue:TheDequeue ( ) operation removes an item from the front of the queue. A Dequeue
operation on an empty stack results in an underflow.

39 Data Structures and Algorithms


7. Dynamic Queue Implementation:
a) Queue Class definition:

class DynQueue{
private:
structqueueNode
{
intnum;
queueNode *next;
};
queueNode *front;
queueNode *rear;
public:
DynQueue();
~DynQueue();
void enqueue();
void dequeue();
bool isEmpty();
void displayQueue();
void makeNull();
};

b) Constructor:

DynQueue::DynQueue()
{
front = NULL;
rear = NULL;
}

c) Enqueue() function:

void DynQueue::enqueue()
{
queueNode *ptr;
ptr = new queueNode;
cout<<"Enter Data";
cin>>ptr->num;
ptr->next= NULL;
if (front == NULL)
{
front = ptr;
rear = front;

40 Data Structures and Algorithms


}
else
{
rear->next=ptr;
rear = ptr;
}
}

d) Dequeue( ) Function:

void DynQueue::dequeue()
{
queueNode *temp;
temp = front;
if(isEmpty())
cout<<"Queue is Empty";
else
{
cout<<"data deleted="<<temp->num;
front = front->next;
delete temp;
}
}

8. Exercises:

Exercise 6.1:

Write a menu driven program to perform different operations with queue such aEnqueue ( ),

Dequeue( ) and DisplayQueue( ).

41 Data Structures and Algorithms


Exercise 6.2:

In this Exercise, you have to take a single string as input. Using this input string, you have to create
multiple queues in which each queue will comprise of separate word appeared in input string. At the
end, you will again concatenate all queues to a single queue.

Example:

String = “Data Structure and Algo”


Q1 = D → a → t → a
Q2 = S → t → r → u → c → t → u → r → e
Q3 = a → n → d
Q4 = A → l → g → o
At the end concatenate all queues and display them.
Q1 → Q2 → Q3 → Q4

Exercise 4.3:

Write a program to demonstrate a printer queue in which jobs for printing are added on the basis of
priority. Each printing job should have name (e.g. A, B, C, D …..) and priority value (e.g. 1=High,
2=Medium, 3=Low). If two jobs has same priority then FIFO rule should be applied.

front A B A C rear

1 2 2 3

42 Data Structures and Algorithms


9. Web Resources:
http://www.cprogramming.com/tutorial/computersciencetheory/queue.html
http://www.sourcetricks.com/2008/07/c-queues.html#.VA66h8KSxcw
http://www.cppforschool.com/tutorial/dynamic-queue.html

10. Video Resources:


http://www.youtube.com/watch?v=zQZMc8FXPYY
www.youtube.com/watch?v=dpg-ULnNnnE

11. Summary:
This lab session introduces the concepts of queues. This lab helps students in implementing queues
using dynamic allocation.

43 Data Structures and Algorithms


EXPERIMENT 7a – RECURSION
1. Objectives:
(a). Understanding the concepts of recursion and its practical usage
(b). Implementation of recursion
2. Time Required: 3 hrs
3. Software Required:
(a). Windows
(b). Microsoft Visual Studio 2012
4. Recursion:Recursion is a programming technique in which procedures and functions call
themselves. When a function calls itself, it is making a recursive call. This approach can be
applied to solve many types of problems. Most computer programming languages support
recursion by allowing a function to call itself within the program.

5. Recursive Call:A function call in which the function being called is the same as the one making
the call.

6. Base Case:

 The case for which the solution can be stated non-recursively


 The case for which the answer is explicitly known.

7. Recursive Case:A recursive function definition also contains one or more recursive cases;
meaning input(s) for which the program recurs (calls itself).
The job of the recursive cases can be seen as breaking down complex inputs into simpler ones. In
a properly-designed recursive function, with each recursive call, the input problem must be
simplified in such a way that eventually the base case must be reached.
For example, the factorial function can be defined recursively by the equations 0! = 1 and, for all
n > 0, n! = n (n − 1)! None of equation by itself constitutes a complete definition, the first is the
base case, and the second is the recursive case.

44 Data Structures and Algorithms


8. Exercises:

Exercise 7.1:
Write a function to calculate triangular number using recursion.
Int trinum(int x);
trinum(4)=10 i.e. 4+3+2+1+0=10

Exercise 7.2:

Create a recursive function for Fibonacci series and a program for calculating it. In
mathematics, the Fibonacci numbers are the numbers in the following integer sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21
By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent number is the
sum of the previous two. In mathematical terms, the sequence Fn of Fibonacci numbers is
defined by the recurrence relation F(n) = F(n-1) + F(n-2) with seed values F(0) = 0 and F(1)
=1

45 Data Structures and Algorithms


Exercise 7.3:
Write a recursive function to display the data members of linked List in reverse order.

Exercise 7.4:
Write a program to reverse a number.

9. Web References:
http://www.cplusplus.com/articles/D2N36Up4/
http://www.danzig.us/cpp/recursion.html
http://www.learncpp.com/cpp-tutorial/710-recursion/

10. Video Link:


www.youtube.com/watch?v=R-SraYQDL8M
www.youtube.com/watch?v=NvVYd08NUXI
www.youtube.com/watch?v=DjLCaQVt_Xk

11. Summary:
This lab introduces students with the concepts of recursion. It allows them to understand the
implementation of recursion and its practical uses.

46 Data Structures and Algorithms


EXPERIMENT 7b – TOWER OF HANOI
1. Objectives:
Implementation of algorithm for Tower of Hanoi

2. Time Required: 3 hrs


3. Software Required:
(a). Windows
(b). Microsoft Visual Studio 2012
4. Tower of Hanoi:Tower of Hanoi is a mathematical puzzle invented by a French Mathematician
Edouard Lucas in 1883. A tower of Hanoi is based on Recursion. Suppose we are given with some
towers, and that on one tower we have already placed some rings. The rings are placed according
to the descending order of magnitude. The problem is to; place all these rings on another tower,
such that the rings are kept in the order, even now.

5. Algorithm:In this problem, there are pegs say A, B and C. There are n discs on peg A of different
diameters and are placed one above the other such that always a smaller disc is placed above the larger disc.
The two pegs B and C are empty. All the discs from peg A are to be transferred to peg C using peg B as
temporary storage. The rules to be followed while transferring the discs are

• Only one disc is moved at a time.

• Smaller disc is on top of the larger disc at any time.

• A disc can be moved from one peg to another.

If there is only one disc, move that disc from A to C. If there are two discs, move the first disc from A to B,
move the second from A to C, then move the disc from B to C. In general, to move n discs from A to C, the
recursive technique consists of three steps:

• Move n-1 discs from A to B.

• Move nth from A to C.

• Move n-1 discs from B to C.

6. Pseudo code:
MoveDisc(whichDisc, frompeg, topeg)
{
Cout<<"Move ring"+ whichDisc+"frompeg"+frompeg+"topeg"+topeg);
}
MoveTower( height, frompeg, topeg, usingpeg) Mission : go from A to C
{
MoveTower( height-1, frompeg,usingpeg, topeg); First going(with n-1 discs) from A to B using C
MoveDisc( height, frompeg, topeg); Printing the nth disc
MoveTower( height-1, usingpeg, topeg,frompeg); Then going from B to C using A
}

47 Data Structures and Algorithms


7. Exercises:

Exercise 7.5:
Write a recursive function to implement the algorithm of tower of Hanoi.

8. Web References:
http://en.wikipedia.org/wiki/Tower_of_Hanoi
http://www.dsalgo.com/2013/02/towers-of-hanoi.html

9. Video Link:
www.youtube.com/watch?v=5QuiCcZKyYU
www.youtube.com/watch?v=5_6nsViVM00

10. Summary:
This lab introduces students with practical resolution of a well-known problem using concepts of
Data Structure and Algorithms.

48 Data Structures and Algorithms


EXPERIMENT 8 – SORTING
1. Objectives:
(a). Learning different sorting algorithms
(b). Implementation of selection, insertion, bubble and merge sort.
2. Time Required: 3 hrs
3. Software Required:
(a). C++
(b). Windows
(c). Microsoft Visual Studio 2012
4. Sorting: Sorting is the process of arranging values in any particular order. The order can be
ascending or descending.
5. Selection sort: is a sorting algorithm which works as follows:
 Find the minimum value in the list
 Swap it with the value in the first position
 Repeat the steps above for remainder of the list (starting at the second position)

Pseudo code:

for(i=0; i<n; i++)

Put the next smallest element in location data[i]

6. Insertion Sort:This algorithm takes one value at a time and builds up another sorted list of values.
It helps if you can imagine what you do when you play a game of cards: you pick a card and insert
it to an already sorted list of cards.

Pseudo code:

insertionSort(array A)
{This procedure sorts in ascending order.}
begin
for i := 1 to length(A)-1 do
begin
value := A[i];
j := i - 1;
done := false;
repeat
{ To sort in descending order simply reverse
the operator i.e. A[j] < value }
if A[j] > value then
begin
A[j + 1] := A[j];
j := j - 1;
if j < 0 then
done := true;
end

49 Data Structures and Algorithms


else
done := true;
until done;
A[j + 1] := value;
end;
end;

7. Bubble Sort:This algorithm looks at pairs of entries in the array, and swaps their order if needed.
After the first step of the algorithm the maximal value will "bubble" up the list and will occupy the
last entry. After the second iteration, the second largest value will "bubble" up the list and will
occupy the next to last entry, and so on.

Pseudo code:

for (i=n-1; i>=0; i--)


for (j=0; j<i; j++)
if (data[j] > data[j+1])
swap(data[j], data[j+1])

8. Merge Sort:This recursive algorithm belongs to the very important divide-and-conquer paradigm.
It consists of the following steps:
 Divide-the elements to be sorted into two groups of equal (or almost equal) size.
 Conquer - Sort each of these smaller groups of elements (by recursive calls).
 Merge - Combine the two sorted groups into one large sorted list.

Pseudo code:
funcmergesort( var a as array )
if ( n == 1 ) return a

var l1 as array = a[0] ... a[n/2]


var l2 as array = a[n/2+1] ... a[n]

l1 = mergesort( l1 )
l2 = mergesort( l2 )

return merge( l1, l2 )


end func

func merge( var a as array, var b as array )


var c as array

while ( a and b have elements )


if ( a[0] > b[0] )
add b[0] to the end of c

50 Data Structures and Algorithms


remove b[0] from b
else
add a[0] to the end of c
remove a[0] from a
while ( a has elements )
add a[0] to the end of c
remove a[0] from a
while ( b has elements )
add b[0] to the end of c
remove b[0] from b
return c
end func

9. Exercises:

Exercise 8.1:

Write a program to sort a given array by using the insertion sort.

Exercise 8.2:

Write a program to sort a given array by using the bubble sort.

51 Data Structures and Algorithms


Exercise 8.3:

Write a program to sort a given array by using the merge sort.

10. Web Resources:


https://www.cs.auckland.ac.nz/software/AlgAnim/sorting.html
http://www.cprogramming.com/algorithms-and-data-structures.html
http://www.studytonight.com/data-structures/introduction-to-sorting

11. Video Resources:


www.youtube.com/watch?v=P00xJgWzz2c
http://video.mit.edu/watch/blossoms-sorting-algorithms-10260/

12. Summary:
This lab introduces students with the concepts of sorting. It also helps them in implementing
different sorting algorithms such as bubble, merge, insertion and selection sort.

52 Data Structures and Algorithms


EXPERIMENT 9 – SEARCHING-LINEAR AND BINARY
1. Objectives:
(a). Understand different searching Algorithms
(b). Implement sequential search and binary search.
2. Time Required: 3 hrs
3. Software Required:
(a). C++
(b). Windows
4. Searching:Searching is the process of finding a particular data in the collection.
5. Sequential search:It is a list or array begins at the beginning of the list or array and continues
until the item is found or the entire list or array has been searched.

Pseudocode:
LINEAR(DATA,N, ITEM,LOC)
Set DATA[N+1] = ITEM
Set LOC = 1
Repeat while DATA[LOC] !=ITEM
Set LOC = LOC +1
If LOC = N+1, then Set LOC =0
Exit.

6. Binary search:It looks for an item in a list using a divide-and-conquer strategy.


 Binary search algorithm assumes that the items in the array being searched are sorted
 The algorithm begins at the middle of the array in a binary search
 If the item for which we are searching is less than the item in the middle, we know that the
item won’t be in the second half of the array
 Once again we examine the “middle” element
 The process continues with each comparison cutting in half the portion of the array where the
item might be

Pseudo code:
BINARY(DATA,LB,UB,ITEM,LOC)

Set BEG=LB, END=UB, and MID= INT((BEG+END)/2)


Repeat Steps 3 and 4 while BEG<=END and DATA[MID]!=ITEM
if ITEM<DATA[MID] then
set END=MID – 1
else
set BEG = MID +1
Set MID = = INT((BEG+END)/2)
if DATA[MID]=ITEM, then
set LOC = MID
else
set LOC = NULL
Exit.

53 Data Structures and Algorithms


7. Exercises:

Exercise 9.1:

Create function for each algorithm using Array:


 Linear search
 Binary search
Input list of numbers: 6 13 14 25 33 43 51 53 64 72 84 93 95 96 97

Exercise 9.2:

Write a program to search an element linearly from the entered numbers. Also, indicate its
position in case the element is found or unavailability.

54 Data Structures and Algorithms


Exercise 9.3:

Write a program to demonstrate binary search. Use character array and store 10 names. This
program prompts the user to enter ten names. They are stored in ascending order the
name[15][10] the fn[15] is used to store the name which we want to search.

8. Web Resources:
http://algorithms.openmymind.net/search/linear.html
http://www.csit.parkland.edu/~mbrandyberry/CS1Java/Lessons/Lesson27/BinarySearch.htm

9. Video Links:
www.youtube.com/watch?v=vohuRrwbTT4
http://tune.pk/video/2451896/binary-search-tree-implementation-in-cc

10. Summary:
This lab introduces students with the search algorithms. It helps students in implementing binary
search and linear search algorithms.

55 Data Structures and Algorithms


EXPERIMENT 10 – BINARY SEARCH TREE
1. Objectives:
(a). Understand concepts and usages of binary search tree
(b). Practice the implementation of binary search tree
2. Time Required: 3 hrs
3. Software Required:
(a). C++
(b). Windows
4. Binary Search Trees: Stores keys in the nodes in a way so that searching, insertion and deletion
can be done efficiently. Binary search tree is either empty or each node N of tree satisfies the
following property

 The Key value in the left child is not more than the value of root
 The key value in the right child is more than or identical to the value of root
 All the sub-trees, i.e. left and right sub-trees follow the two rules mention above.

5. Minimum:The minimum element of a binary search tree is the last node of the left roof
6. Maximum: The maximum element is the last node of the right roof.
7. Exercises:

Exercise 10.1:
Write a menu driven program for inserting and deleting an element of binary search tree.

56 Data Structures and Algorithms


Exercise 10.2:
Write a menu-driven program to traverse the binary search tree by using the following:
 Preorder traversals
 Inorder traversals
 Postorder traversals

8. Web References:
http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/binarySearchTree.htm
https://www.cs.auckland.ac.nz/~jmor159/PLDS210/niemann/s_bin.htm
http://www.sanfoundry.com/cpp-program-implement-binary-tree-2/

9. Video References:
www.youtube.com/watch?v=COZK7NATh4k
www.youtube.com/watch?v=5vwVuLMzqxQ

10. Summary:
This lab introduces students with the concepts of Binary search tree, its practical usages and its
implementation.

57 Data Structures and Algorithms


EXPERIMENT 11 – GRAPH
1. Objectives:
(a). Understand the concepts if graphs
(b). Implementation of graphs
2. Time Required: 3 hrs
3. Software Required:
(a). C++
(b). Windows
4. Graph:
Graph is a data structure that consists of a set of nodes (vertices) and a set of edges that relate the
nodes to each other. The set of edges describes relationships among the vertices.
A graph G is defined as follows:
G = (V,E)
V(G): a finite, nonempty set of vertices
E(G): a set of edges (pairs of vertices)

5. Graph Traversing:Traversing a graph consists of visiting each vertex only one time. We can
traverse the graph by two ways:
 Depth first search
 Breadth first search

6. Breadth First Search: Breadth-first search (BFS) is a graph search algorithm that begins at the root
node and explores all the neighbouring nodes. Then for each of those nearest nodes, it explores their
unexplored neighbour nodes, and so on, until it finds the goal.

Pseudo code:

Input: A graph G and a root v of G

----------------------------------------------------------------------------------------------------------------

procedure BFS(Graph,v):
create a queue Q
enqueue v onto Q
mark v
while Q is not empty:
t ← Q.dequeue()
for all edges e in G.incidentEdges(t) do
o ← G.opposite(t,e)
if o is not marked:
mark o
enqueue o onto Q

7. Depth First Search: Depth-first search (DFS) is an algorithm for traversing or searching a tree,
tree structure, or graph. One starts at the root (selecting some node as the root in the graph case) and
explores as far as possible along each branch before backtracking.

58 Data Structures and Algorithms


8. Exercises:

Exercise 11.1:
Create the following class Graph. Implement all function listed in class and test using menu
driven program.

class Graph

{
private:
structGNode
{
int data;
GNode *ptr;
bool visited;
};
GNode *GList;
public:
graph();
void Create();
voidInsertVertex(int);
voidInsertEdge();
voidDisplayVertices();
voidDeleteVertex();
voidDeleteEdges();
boolSearchVertex();
boolSearchEdge();
voidBFSTraversal();
voidDFSTraversal();

};

59 Data Structures and Algorithms


Exercise 11.2:

Write a function called DelAllMinEdges( ). This function will first search all the edges in the
graph and will delete all those edges having minimum weight. Consider that graph is
implemented using Adjacency List. Consider the following structure for both Vertices and
Edges
StructGNode
{
int weight;
GNode *ptr;
}*GList;

Note: In the following example DelAllMinEdges( ) will delete the edge between vertex 4 to 3
and 1to 4 because of minimum weight.

9. Web References:
http://www3.cs.stonybrook.edu/~algorith/files/graph-data-structures.shtml
http://interactivepython.org/runestone/static/pythonds/Graphs/graphintro.html
https://www.cs.auckland.ac.nz/~jmor159/PLDS210/mst.html

10. Video References:


www.youtube.com/watch?v=vfCo5A4HGKc
www.youtube.com/watch?v=dJc38Vh2TrY

11. Summary:
This lab introduces students with the concepts of graphs and their implementation.

60 Data Structures and Algorithms


EXPERIMENT 12 – GRAPH- MST & DIJKSTRA ALGO
1. Objectives:
(a). Understand the concepts and implementation of MST
(b). Find shortest path in Graph using Dijkstra Algo.
2. Time Required: 3 hrs
3. Software Required:
(a). Microsoft Windows
(b). C++
4. Spanning Tree: A spanning tree of a graph is an undirected tree consisting of only those edges
necessary to connect all the nodes in the original graph.
5. Minimum Spanning Tree (MST):A minimum spanning tree is a subgraph of an undirected
weighted graph G, such that
• it is a tree (i.e., it is acyclic)
• it covers all the vertices V
– contains |V| - 1 edges
• the total cost associated with tree edges is the minimum among all possible spanning trees

6. Kruskal’sAlgorithm:Kruskal's algorithm is an algorithm in graph theory that finds a minimum


spanning tree for a connected weighted graph. This means 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.At
the termination of the algorithm, the “forest” has only one component and forms a minimum
spanning tree of the graph.
Algorithm:
• create a forest F (a set of trees), where each vertex in the graph is a separate tree as well
• create a set S containing all the edges in the graph
• while S is nonempty
– remove an edge with minimum weight from S
– if that edge connects two different trees, then add it to the forest, combining two
trees into a single tree
– otherwise discard that edge
• In the subsequent example, a green edge means it has been included into the forest of trees
that will ultimately form a single, minimum spanning tree

7. How to Generate a MST?

61 Data Structures and Algorithms


8. Dijkstra Algorithm - Shortest Path Calculation:This algorithm is used to find the shortest path
between nodes. The “shortest path” may be computed on the basis of number of hops, the distance,
bandwidth available, queue lengths etc. It is widely used in Dynamic routing algorithm.

9. Dijkstra Algorithm:
1. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity
for all other nodes.
2. Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited nodes
called the unvisited set consisting of all the nodes except the initial node.
3. For the current node, consider all of its unvisited neighbours and calculate
their tentative distances.
4. When we are done considering all of the neighbours of the current node, mark the current node
as visited and remove it from the unvisited set. A visited node will never be checked again; its
distance recorded now is final and minimal.
5. If the destination node has been marked visited (when planning a route between two specific
nodes) or if the smallest tentative distance among the nodes in the unvisited set is infinity
(when planning a complete traversal), then stop. The algorithm has finished.
6. Set the unvisited node marked with the smallest tentative distance as the next "current node"
and go back to step 3.

10. Exercises:

Exercise 12.1:
Write a program, which reads an adjacency matrix representation of a graph and applies
Kruskal’s algorithm to find minimum spanning tree of the input graph.

Exercise 12.2:
Consider the following graph and calculate the shortest path using Dijkstra Algorithm from
V0 to V3. Show all the steps involved in the calculations.

62 Data Structures and Algorithms


11. Web References:
http://www3.cs.stonybrook.edu/~skiena/combinatorica/animations/dijkstra.html
https://www.cs.auckland.ac.nz/software/AlgAnim/dijkstra.html
https://www.ics.uci.edu/~eppstein/161/960206.html

12. Video References:


http://freevideolectures.com/Course/2279/Data-Structures-And-Algorithms/31
www.youtube.com/watch?v=k9jemw3SZe0
www.youtube.com/watch?v=WN3Rb9wVYDY

13. Summary:
This lab introduces students with MST and DijkstraAlgorithm. It also helps students in solving the
shortest path algorithm using Dijkstra Algorithm.

63 Data Structures and Algorithms


EXPERIMENT 13 – HASHING
1. Objectives:
To learn the concepts of hashing and to implement them
2. Time Required: 3 hrs
3. Software Required:
(a). C++
(b). Windows
4. Hashing:Hashing is technique that maps each key to a location in memory. This method is useful
in searching.

5. Hashing Function:A simple function is applied to the key to determine its place in the collection.
6. Hash Table: A hash table is simply an array that is addressed via a hash function. Here Hash
Table is an array with 8 elements. Each element is a pointer to a linked list of numeric data. The
hash function for this example simply divides the data key by 8, and uses the remainder as an
index into the table. This yields a number from 0 to 7. Since the range of indices for Hash Table
is 0 to 7, we are guaranteed that the index is valid.

7. Exercises:

Exercise 13.1:

Write a program to prepare the hashing table as shown above. Take the elements through the
keyboard and map them in hash table.

64 Data Structures and Algorithms


Exercise 13.2:

Write a function deleteNode deletes and frees a node from the table.

Exercise 13.3:

Wite a function findNode searches the table for a particular value.

8. Web Resources:
https://www.cs.auckland.ac.nz/software/AlgAnim/hash_func.html
http://datastructuresnotes.blogspot.com/2009/03/hashing-hash-data-structure-and-hash.html

9. Video Resources:
www.youtube.com/watch?v=MfhjkfocRR0
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-
algorithms-sma-5503-fall-2005/video-lectures/lecture-7-hashing-hash-functions/

10. Summary:
This lab introduces students with hash functions, hash tables, their uses and their implementation.

65 Data Structures and Algorithms


EXPERIMENT 14 – HUFFMAN CODING COMPRESSION ALGORITHM
1. Objectives:
To implement basic Huffman Coding Compression Algorithm.
2. Time Required: 3 hrs
3. Software Required:
(a). C++
(b). Windows

TASK:
Build the Huffman coding tree for the following sequence of characters:

EIEIOEIEIOEEIOPPEEEEPPSSTTEEEPPPPTTSSEIEIOEIEIOEEIOPPEEEEEEEPPPPTTSS

Steps:
For a given sequence of letters:
1. Count the frequency of occurrence for the letters in the sequence.
2. Sort the frequencies into increasing order.
3. Build the Huffman coding tree:
_ choose the two smallest values, make a (sub) binary with these values.
_ accumulate the sum of these values
_ replace the sum in place of original two smallest values and repeat from 1.
_ construction of tree is a bottom-up insertion of sub-trees at each iteration.
4. Making the codes: Traverse tree in top-down fashion
_ Assign a 0 to left branch and a 1 to the right branch
_ Accumulate 0s and 1s for each character from root to end vertex.
_ This is the Huffman code for that character.

66 Data Structures and Algorithms


“I hear and I forget,
I see and I remember,
I do and I understand”

Confucius

You might also like