Vous êtes sur la page 1sur 67

Department of Computer Science and

Data Structures

Lab Manual (CSE182)

Student Name : .

Register Number : .

Section :
..

1
TABLE OF CONTENTS

S.No Topic Page No.

1 Bonafide Certificate 3

2 Experiment Evaluation Summary 4

3 Course Plan 5

4 Introduction 11

Experiments

5 Simple C Programs 12

6 C Programs using structures and pointers 17

7 Array Implementation of List ADT 23

8 Linked list Implementation of List ADT 28

9 Array implementation of Stack and Queue 33

10 Linked implementation of Stack and Queue 40

11 Applications of stack 46

12 Binary Search Trees 53

13 Sorting Technique0073 58

14 Searching Techniques 62

15 Shortest Path algorithm 65

16 Minimum Spanning Tree algorithms 69

Anand Nagar,Krishnankoil-626126
2
Srivilliputtur(via),Virudhunagar(Dt),Tamil Nadu

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

BONAFIDE CERTIFICATE

Bonafide record of work done by


of _ in
during even/odd semester in academic year

Staff In-charge Head of the Department

Submitted to the practical Examination held at Kalasalingam University, Krishnankoil on

________________________________
____________

REGISTER NUMBER

Internal Examiner External Examiner

EXPERIMENT EVALUATION SUMMARY

Name: Reg No :

3
Class : Faculty :

Marks Faculty
S.No Date Experiment
(100) Signature

1 Simple C Programs

2 C Programs using structures and


pointers

3 Array Implementation of List ADT

4 Linked list Implementation of List ADT

5 Array implementation of Stack and


Queue

6 Linked implementation of Stack and


Queue

7 Applications of stack

8 Binary Search Trees

9 Sorting Techniques

10 Searching Techniques

11 Shortest Path algorithm

12 Minimum Spanning Tree algorithms

COURSE PLAN

Courset with code Data Structures - CSE182

4
Course B.Tech (CSE)
Semester / Sec II / A-D
Course Credits 2
Course Coordinator Dr. P.Deepalakshmi
Module Coordinator Dr. K. Kartheeban
Programme Dr. R. Ramalakshmi
Coordinator

COURSE DESCRIPTION

The main objective of this course is to provide an introduction to basic data


structures and its operations using C programming language. The course is
designed to develop skills to design and analyze simple linear and nonlinear data
structures. It strengthens the ability of the students to identify and apply the
suitable data structure for the given real world problem. It enables them to gain
knowledge in practical applications of data structures.

COURSE PRE-REQUISITES : Programming Languages using C (CSE102)

COURSE OBJECTIVE:

1. To understand the importance of structures, functions, arrays and pointers,


and their basic usability in different applications.
2. To get familiar with utilization of linear data structure techniques in problem
solving.
3. To apply the relevant searching and sorting techniques to solve various
computing problems.
4. To decide a suitable data structure to solve a real world problem
PROGRAMME SPECIFIC OUTCOMEs

DESCRIPTION
PSOs

Problem-Solving Skills: The ability to apply mathematics, science and


PSO1 computer engineering knowledge to analyze, design and develop cost
effective computing solutions for complex problems with environmental
considerations.
Professional Skills: The ability to apply modern tools and strategies in
PSO2 software project development using modern programming environments to
deliver a quality product for business accomplishment.
Communication and Team Skill: The ability to exhibit proficiency in oral
PSO3 and written communication as individual or as part of a team to work
effectively with professional behaviors and ethics.
Successful Career and Entrepreneurship: The ability to create a
PSO4 inventive career path by applying innovative project management
techniques to become a successful software professional, an entrepreneur
5
or zest for higher studies.

PROGRAMME OUTCOMES:

POs DESCRIPTION
PO1 Ability to apply knowledge of mathematics, science and computer
engineering to solve computational problems.
PO2 Identify, formulate, analyze and solve complex computing problems.
PO3 Capability to design and develop computing systems to meet the
requirement of industry and society with due consideration for public
health, safety and environment.
PO4 Ability to apply knowledge of design of experiment and data analysis to
derive solutions in complex computing problems and society with due
consideration for public health, safety and environment.
PO5 Ability to develop and apply modeling, simulation and prediction tools
and techniques to engineering problems.
PO6 Assess and understand the professional, legal, security and societal
responsibilities Relevant to computer engineering practice.
PO7 Ability to understand the impact of computing solutions in economic,
environmental and societal context for sustainable development.
PO8 Applying ethical principles and commitment to ethics of IT and software
profession.
PO9 Ability to work effectively as an individual as well as in teams.
PO10 Effectively communicating with technical community and with society.
PO11 Demonstrating and applying the knowledge of computer engineering and
management principles in software project development and in
multidisciplinary areas.
PO12 Understanding the need for technological changes and engage in life-long
learning.

COURSE OUTCOMES

S.N DESCRIPTION
O

Understand Demonstrate the importance of basic structured


CO1 programming in solving problems

6
Design and Implement the linear and non-linear data structure and
CO2 its operations

Implement and analyze the searching and sorting algorithms.


CO3

Implement shortest path algorithms and finding minimum cost


CO4 spanning trees using graphs

Apply leant data structures to real world problems


CO5

MAPPING OF PO and PSO:

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO1 PO1 PO1
0 1 2

PSO S S S S
1

PSO S S S M S
2

PSO S M S S S
3

PSO M S M M M S S
4

MAPPING OF CO AND PO:

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO1 PO1 PO1
0 1 2

CO1 S S

7
S S
CO2

CO3 S S S S M

CO4 S S S S S

CO5 S S S S M

S- Strong Correlation M- Medium Correlation L Low Correlation

WEB RESOURCES:

S.No Units Websites

1. Introductio 1. http:/www.cs.cf.ac.uk/Dave/C/
n To Data 2. http://www.lysator.liu.se/c/bwk-tutor.html
Structures 3. http://en.wikibooks.org/wiki/Data_Structures/Introduction
4. http://www.eskimo.com/~scs/cclass/notes/top.html
5. http://kumarharmuscat.tripod.com/ds/building_linked_list.sw
f
2 Stack, 1. http://www.c4learn.com/c-programs/c-program-to-
Queues implement-stack-operations-using-array.html
and 2. http://www.engineersgarage.com/c-language-
programs/stack-push-pop-implementation-using-arrays
Hashing
3. https://gist.github.com/mycodeschool/7510222
4. http://www.sanfoundry.com/wp-content/cache/ supercache/
www.sanfoundry.com/c-program-queue-using-array/
3 Trees 1. http://kumarharmuscat.tripod.com/ds/schedule.html
2. http://interactivepython.org/runestone/static/pythonds/Trees
/trees.html
3. http://www.geeksforgeeks.org/applications-of-tree-data-
structure/
4 Sorting and 1. http://www.cosc.canterbury.ac.nz/mukundan/dsal/ISort.html
Searching 2. http://epaperpress.com/sortsearch/download/sortsearch.pdf
3. https://www.cs.auckland.ac.nz/~jmor159/PLDS210/niemann
/s_man.pdf
4. http://www.cs.pitt.edu/~kirk/cs1501/animations/Sort2.html
5 Graphs 1. http://www.brpreiss.com/books/opus4/html/page557.html
2. http://www.algolist.net/Algorithms/Graph_algorithms/Undire
cted/Depth_first_search
3. http://www.brpreiss.com/books/opus4/html/page535.html
4. http://www.math.uaa.alaska.edu/~afkjm/cs411/handouts/gr
aphs.pdf

LIST OF EXPERIMENTS
8
Exp No. of Cum.
t. NAME OF THE EXPERIMENT Hours Hours
No
Introductory experiments
Simple C Programs
1 Programs using recursion and its types - Factorial, 3 3
Fibonacci, GCD, Reversing array elements
C Programs using structures and pointers : Book
2 3 6
database, Employee Database, Bank Database
Linear Data Structures
Array Implementation of List ADT- Creation, Insertion,
3 3 9
Deletion, Search, Display operations
Linked list Implementation of List ADT Creation List,
4 3 12
Add, Insert, Delete , Search given data
Array implementation of
5 3 15
a. Stack ADT b. Queue ADT
Linked List Implementations of
6 3 18
a. Stack ADT b. Queue ADT
Applications of stack
a. Checking Balanced Parentheses using stack
7 6 24
b. Evaluating Postfix expressions using stack
c. Converting Infix to Postfix form
Implementation of Non-Linear Data Structures ,Sorting and Searching
Techniques
8 Binary Search Trees implementation 3 27
Program to sort set of elements using
9 a) Heap sort 6 33
b) Quick sort
Program to search an element in a list using
10 a) Linear search 3 36
b) Binary search.
Implementation of Graphs
11 Implementation of Dijkstras shortest path algorithm 3 39
Finding Minimum Spanning Tree using
12 a) Kruskals algorithm 6 45
b) Prims algorithm

PROJECTS: (CO5)
1. Project on STUDENT DATABASE and add, delete, update and other operations.
2. Develop using minimum spanning tree for travelling sales man.
3. Implement a magic square puzzle using data structure.
4. Implement Huffmans algorithm using tree in data structure.
9
5. Implement a weighted graph one would like to select cities (vertices) to have
minimum total cost / minimum total length. So one can find a spanning tree
with minimum cost.

ADDITIONAL EXPERIMENTS:
1. Implement array-based circular queue and use it to simulate a producer
consumer problem.(CO1)
2. Counting the number of nodes in singly linked list.(CO2)
3. Implement an expression tree. Produce its pre-order, in-order, and post-order
traversals.(CO2)
4. Implement a backtracking algorithm for Knapsack problem(CO4)
5. Implement a branch and bound algorithm for traveling salesperson
problem(CO4)
6. Implement the recursive algorithm using Tower of Hanoi problem(CO1)
7. Implementation of Depth first ,Breadth First Search Algorithms(CO4)

ASSESSMENT METHOD:

S.N
o Assessment Split up
Regular Lab Exercises (20)
1 Internal Assessment (50 marks)
Model Lab (30)
2 External Assessment (50 marks) End semester Lab (50)
RUBRICS FOR INDIVIDUAL EXPERIMENTS

Modules Unacceptable Fair Acceptable Excellent


Level of Very little background Some Introduction is Introduction
understandi information provided introductory nearly complete, provide
ng or information is information, complete, all necessary
incorrect but still missing some background
(1) missing some minor points(7) principles for the
major experiment(10)
points(4)
Algorithm Several major Algorithm Algorithm is Algorithm is
aspects of the misses one or nearly complete and well
exercise are missing, more major complete, written; provides
student displays a aspects of missing some all necessary
lack of understanding carrying out minor points background
about how to write an the exercise principles for the
algorithm (2) (6) (10) exercise(15)
Design Missing several Written in Written in Program Logic is
principles & important proper logic, proper logic, well written, all
10
Program experimental details still missing important details are covere
Logic or not written in some details are (40)
proper logic in important covered, some
program details minor details
(10) (20) missing (30)
Output Output contains Partial Output is good
errors or are poorly output; but some Output is excellen
constructed, missing some minor (10)
(2) important problems or
output could still be
features(4) improved(7)
Discussion/V Answered for less Answered for Answered for Answered for more
iva than 40% of the 60% of the 60% of the than 90% of the
questions indicating a questions. questions. Still questions
lack of understanding but need some correctly, good
of results incomplete improvements understanding of
(2) understandin (7) results is
g of results is conveyed(10)
still
evident(4)

INTRODUCTION

Data structure is an arrangement of data in a computer's memory or even


disk storage. An example of common data structures are arrays, linked lists,
queues, stacks, binary trees, and hash tables. Algorithms, on the other hand, are
used to manipulate the data contained in these data structures as in searching
and sorting.
C provides us one of the built in data structure, the array. Although efficient
and easily used and understood, arrays often don't provide us with the level of
functionality we need from a data structure. If the quantity of data we need to
store is not well known at compile time, then using arrays could waste memory if
too large, or waste time in resizing at runtime if too small. Several, more abstract,
data structures can be constructed to better serve our needs. Many algorithms
apply directly to a specific data structures. When working with certain data

11
structures you need to know how to insert new data, search for a specified item,
and deleting a specific item.
Commonly used algorithms are useful for searching for a particular data item
(or record), sorting the data and iterating through all the items in a data structure.
This manual is organized in such a way that the students can directly use it in
the laboratory. Each laboratory exercise comprises sections for
1. Aim - Statement of the problem
2. Algorithm
3. C code (To be created by student)
4. Sample Output
5. Result
Student must follow this sequence to conduct any data structures
experiment in the laboratory and should maintain report accordingly. Using the
algorithms given in this manual for every experiment, student can implement in C
language. For using other programming languages, simply follow the same
algorithmic steps and use additional language features, if any. Also, a student is
allowed to follow his own algorithm provided the same should be verified by the
faculty before implementation in laboratory.

Ex .No 1 Simple C programs


Aim:
To write Simple C programs using arrays recursive functions.
Recursive Functions:
Functions are used to encapsulate a set of operations and return information
to the main program or calling routine. A recursive function is a function that calls
itself, thus understanding recursion to understand recursion seems like a call to
itself.
A recursive function is defined as a function that calls itself to solve a
smaller version of its task until a final call is made which does not require a call to
itself. Every recursive function has two major cases, they are,
Base Case: The problem is simple and can be solved directly without
making further calls to same function.
Recursive Case:
i) Given problem is divided in to simpler sub parts
ii) Function calls itself with subparts of the problem obtained in first step.
iii) Result is obtained by combining solutions of simpler subparts.
Base case acts as the terminating condition. If it is not defined, then recursive
function will generate infinite sequence of calls and will lead to error conditions.

12
List of Exercises
1. Write a C program to find factorial of a number using recursion.
2. Write a C program to find the GCD of given two numbers using recursion.
3. Write a C program to generate nth Fibonacci number.
4. Write a C program to reverse array using recursion.

Algorithm:
1. To find the factorial of a given number using linear recursion:
Base case : 0! = 1, 1!=1
Recursive case : N! = N * (N-1)!
i. Get the number N
ii. Call the function factorial for N as result = factorial(N)
iii. Inside the function
a) If N < 0 print factorial is not defined for negative numbers
b) If N==0 or N==1, return 1. //Base case
c) Otherwise, return N*factorial (N-1) // recursive case
iv. The factorial value of N is returned in result and hence print result.

2. To find the GCD of given two numbers using linear recursion


Base case : gcd(a,0) = a
Recursive case : gcd(a,b) = gcd(b,a%b)
i) Get twonumbers a, b
ii) Call the function findgcd for a,b as result=findgcd(a,b)
iii) Inside the function
a) If b == 0, return a as result.
b)Otherwise, return findgcd(b,a%b)
iv) The greatest common divisor of a, b is returned in result and hence print
result

3)To find nth Fibonacci number using binary recursion


Base case : Fib(1) = 0, Fib(2) = 1
Recursive case : Fin(n)=Fib(n-1)+Fib(n-2)
i) Get the number n.
ii) Call result = Fib(n)
iii) Inside the function
a) If n ==1, return 0;
b) If n==2, return 1;
c) Otherwise return Fib(n-1)+Fib(n-2)
iv) The nth Fibonacci number is returned in result and hence print result.

4. To reverse an array using tail recursion


Reversal of an array can be achieved by swapping the first and last
elements and then recursively reversing the remaining elements in the array

i) Get the size as number of elements in an array, A.


ii) Get the elements for the array, A
13
iii) Call function reversearray(A, 0, size-1)
iv) In function reversearray(A, i, j)
a) if (i<j), swap the elements in i and j positions.

tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
b) call same function for i+1 and j-1 with the array as reversearray(A, i+1, j-
1)
v) Print the reversed elements in array using any looping statement

Programs

14
15
Viva Questions

1. What is meant by recursion?


2. State the merits and demerits of recursion>
3. State the types of recursion?
4. When recursion will go indefinite?
5. How recursion is useful in implementing various data structures?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result

Thus the simple program using recursion are done

Ex .No 2 C programs using structures and pointers

Aim

To write Advanced C programs using pointers & structures

Functions:

16
Function is a portion of code within a larger program, which performs a
specific task and can be relatively independent of the remaining code. The syntax
of many programming languages includes support for creating self contained
subroutines, and for calling and returning from them.

Structures:

A structure provides a means of grouping variables under a single name for


easier handling and identification. A structure is declared by using the keyword
struct followed by an optional structure tag followed by the body of the structure.
The variables or members of the structure are declared within the body.

Pointers:

Pointers are variables that hold addresses in C. A pointer is a special type of


variable that contains a memory address rather than a data value. Just as data is
modified when a normal variable is used, the value of the address stored in a
pointer is modified as a pointer variable is manipulated.

A pointer to the variable is passed to the function. The pointer can then be
manipulated to change the value of the variable in the calling routine. It is
interesting to note that the pointer itself is passed by value. The function cannot
change the pointer itself since it gets a local copy of the pointer. However, the
function can change the contents of memory, the variable, to which the pointer
refers. The advantages of passing by pointer are that any changes to variables
will be passed back to the calling routine and that multiple variables can be
changed.

List of Exercises:

a)Creating a structure to represent a book. Include functions to get (use call by


reference) and print the values of single book. Write an appropriate C main.

17
b) Create a structure to represent employee details. Use array to create record for
10 employees. Include function to get and print these 10 employee records. Also
create a function raisesalary to raise the salary of all employees by 20%. Write an
appropriate C main.

c) Write a C program with a structure to represent bank account. Include functions


to get and print account details. Use pointer to structures when passing to
functions.

Algorithm

(Students are instructed to write their own algorithm for these


exercises)

18
Programs

19
20
21
Viva Questions

1. What is the difference between structure and array?


2. What are the uses of pointers in C language?
3. What is the difference between call by reference and call by address?
4. How functions are useful for efficient programming?
5. What is the use of array of structures?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result

Thus the programs using structures, array of structures and pointer to structure as
parameters to functions are done.

Ex.No 3 Array Implementation of List ADT

Aim

To implement a List ADT using arrays.

List ADT

22
A list is a set of ordered or unordered elements. An example of a list is
A1, A2, A3 An. For each element Ai in the list there is a previous element A i-1,
called the predecessor, and an element that follows it, Ai+1, called the successor.
The size of the list is n. The first element has no predecessor and the last element
has no successor.

A list can be implemented using arrays. First, we have to declare an array


ahead of time. Then a set of elements can be assigned to the array positions. To
insert an element x, at a position p in an array, first, the array size has to be
increased by one and then all the elements after the position p have to be shifted
one place downward, and then the element can be inserted at the required
position p.

Consider a list with size =4 stored in array of capacity = 10

10 20 30 40

Assume 10 is at position 1 and we want to insert 25 in position 3. Elements


from 3rd position onwards should be right shifted first as follows.

10 20 30 40

Now 25 can be assigned to 3rd position as follows and size will be now 5.

10 20 25 30 40

If we want to remove the element 20 from the list, then the list will appear as,

10 25 30 40

Since 2nd position is empty, we need to shift elements from 3rd position
towards left. Then the list will appear as below and size will be now 4.

23
10 25 30 40

Any element can be accessed if position is known or otherwise a linear


search can be done to search the position if the element is present in the list.

Algorithm

1. Declare a structure with the members Capacity, Lsize and an array, Arr to
hold list elements. Capacity is the size of array and Lsize is the number of
elements in list.
2. Declare a pointer to structure, L and allocate memory for it.
3. Initialize L->Capacity = 10 (For example) and L->Lsize = 0 and allocate
memory for array, Arr also.
3. To add element to list,
i) Check L->Lsize==L->Capacity
ii) If so, the list is already full and element cant be added to list.
iii) Otherwise, append the element at last position of list and increment list
size by one.
L-Arr[L->Lsize]=element;
L->size ++;

4. To insert an element at position, P

i) Check L->Lsize==L->Capacity
ii) If so, the list is already full and element cant be inserted
iii) Otherwise, move all elements from last position to P, one positionright in
the array.
for(i=L->Lsize-1;i>=P;i--)
L->Arr[i+1]=L->Arr[i];
iv) Increment L->Lsize by one and make L->Arr[P]=element
5. To deletean element from list,
i) Check whether the element is present in the list by linear search in L-
>Arr ii) If not found, print element not found in list to delete
iii) Otherwise
a) Let P be the position of element to be deleted
b) Move all elements from position P+1 to last position one step left in
the array.
for(i=P;i<L->Lsize;i++)
L->Arr[i]=L->Arr[i+1];
c) Decrement L->Lsize by one.
24
6. To search/find an element X in list,
i) Start at position, P=0
ii) Check if L->Arr[P]==X
iii) If so, print found and return the postion P.
iv) Otherwise increment P and go to step ii) if P<L->Lsize.
v) If end of array is reached, print not found.
7. To display the list,
i) Start at position, P=0
ii) Print L->Arr[P];
iii) Increment P and if P < L->Lsize, go to step ii)

Program

25
Viva Questions

1. What is meant by list ADT?


2. How arrays are useful in implementing list ADT?
3. State demerits of implementing list ADT using Arrays?
4. What is meant by time and space complexity?
5. Give the time complexity of search and deletion operation in array version of
List ADT.

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result
Thus the program for array implementation of List ADT is done.
Ex .No 4 Linked List Implementation of List ADT
Aim
To create a C program for implementing List ADT using linked list.
Linked List

26
Linked List is a linear data structure and it is very common data structure
which consists of group of nodes in a sequence which is divided in two parts. Each
node consists of its own data and the address of the next node and forms a chain.
Linked Lists are used to create trees and graphs.

Advantages of Linked Lists

They are a dynamic in nature which allocates the memory when required.

Insertion and deletion operations can be easily implemented.

Stacks and queues can be easily executed.

Linked List reduces the access time.

Disadvantages of Linked Lists

The memory is wasted as pointers require extra memory for storage.

No element can be accessed randomly; it has to access each node


sequentially.

Reverse Traversing is difficult in linked list.

Operations in Linked Lists

1. Adding elements at the end of list

2. Inserting an element after an existing element in the list

3. Deleting an element from the list

4. Searching/Finding an element in the list

5. Displaying the content of list

6. Checking whether list is Empty

27
7. Finding previous element of a given element in list

Algorithm

1. Create a structure Node with data filed and a self reference pointer Next to the
same structure.
2. Create a Node, L which serves as the header in the list. Initially L->Next = NULL
indicating list as empty.
3. To add an element X in to the list
i) Create a new node, TmpNode and assign TmpNode->Next=X
ii) By traversing the list, go the last node, P in the list.
P=L;
While (P->Next!=NULL)
P=P->Next;
iii) Attach new node with last node.
P->Next=TmpNode
4. To insert an element X after a given element, prev
i) Find the node, P containing the element prev in the list
ii) If P== NULL, previous element is not present; so insertion is not
possible.
iii) Otherwise
a) Create a new node, TmpNode and assign TmpNode-
>data=X .
b) Insert TmpNode after P as follows.
TmpNode->Next = P->Next
P->Next=TmpNode
That is attaching the nodes after P with TmpNode and attaching TmpNode with P.
5. To delete an element X from the list
i) Find the previous node, P to the node containing the element X
ii) If P== NULL, X is not present in list; so deletion is not possible.
iii) Otherwise, attach P with next node of node containing X in list.
TmpNode = P->Next;
P->Next=TmpNode->Next;
free(TmpNode);
6. To find for an element, X in the list
i) Let P be the first node in the list, P=L->Next
ii) If P->data == X, return P.
iii) Otherwise, move to next node as P= P->Next and repeat step ii)
iv) If P==NULL, X is not found in list.
7. To display the content of the List, L
i) If L->Next == NULL, print list is empty and return.
ii) Otherwise, Let P=L->Next
iii) print P->data
iv) Move to next node as P=P->Next
v) If P!=NULL, repeate from step iii).d

28
Program

29
30
Viva Questions

1. What is meant by node?


2. What are the applications of linked list?
3. What are all the various types of linked list?
4. How linked is organized in computer memory?
5. Give the time complexity of various operation of linked list?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result

Thus the program for implementing linked list is done.

Ex .No 5a Array Implementation of Stack ADT


Aim:
To implement stack data structure using arrays.
Stack:
A stack is a list in which all insertions and deletions are made at one end,
called the top. It is a collection of contiguous cells, stacked on top of each other.
The last element inserted into the stack will be the first to be removed. Thus
stacks are said to follow the discipline Last In, First Out (LIFO) lists.
The operations that can be performed on a stack are Push, Pop, ViewStack
and ViewTop. Push Operation inserts an element at the top of the stack. Pop
deletes an element at the top most position inthe stack. ViewTop simply examines
and returns the value at top of stack without deleting it. Pushing in an already
filled stack and popping from an empty stack results in serious errors. Before any
insertion, the value of top is initialized to -1 indicating that stack is empty.
Algorithm:
1. Declare a structure called Stack that contains the TopOfStack and the
Capacityand Arrayfields.
2. Arraycan beeither static dynamic as pointer to array.
31
3. Initialize TopOfStack for the stack as -1(empty stack).
4. To push an element into the stack, check whether TopOfStack + 1 =
Capapcity.
If so, say the stack is full and no more push is possible.
Otherwise, increment TopOfStack and then set Array[++TopOfStack]=X.
5. To pop an element from the array, check TopOfStack.
IfTopOfStack = -1, say stack is empty.
Otherwise, return Array[TopOfStack] and then decrement TopOfStack.
6. To view the element at top,
check TopOfStack.
IfTopOfStack = -1, say stack is empty.
Otherwise, return Array[TopOfStack]
7. To view all elements in stack,
check TopOfStack.
IfTopOfStack = -1, say stack is empty.
Otherwise, using any looping statement display from Array[TopOfStack]to
Array[0]

Program

32
Viva Questions

1. What is stack data structure?


2. List out the applications of stack.
3. In what ways stack can be implemented?
4. Is it possible to have multiple stacks in a single array?
5. What does TopOfStack signify?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result
Thus C program for implementation of stack using array is done.
Ex. No. 5b Array Implementation of Queue ADT
Aim
To implement a Queue data structure using an array
Queue
A Queue is an ordered collection of items from which items may be deleted
at one end (called the frontof the queue) and into which items may be inserted
at the other end (the rearof the queue). Queues remember things in first-in-first-
out (FIFO) order. The basic operations in a queue are i)Enqueue Adding item to
the end of queue, ii)Dequeue - Removing an item from the front of the queue. In
33
addition to this we can perform ViewFront, ViewQueue, checking isEmpty, IsFull as
additional functions.
Array implementation of Queue ADT
A queue is implemented using a one dimensional array. Front is the array
index of the first element of the queue. Rear is the array index of the last element
which is recently inserted into the queue.
In a normal Queue Data Structure, we can insert elements until queue
becomes full. But once if queue becomes full, we cannot insert the next element
until all the elements are deleted from the queue. For example consider the queue
below...

Now consider the following situation after deleting three elements from the
queue...

This situation also says that Queue is Full and we cannot insert the new
element because, 'rear' is still at last position. In above situation, even though we
have empty positions in the queue we cannot make use of them to insert new
element. This is the major problem in normal queue data structure. To overcome
this problem we use circular queue data structure.
Circular Queue is a linear data structure in which the operations are
performed based on FIFO (First In First Out) principle and the last position is
connected back to the first position to make a circle.

Algorithm:
1. Declare a structure called Queue that contains and Array, Capacity, QSize,
Front and Rear. Arraycan beeither static dynamic as pointer to array. Capacity
represents the maximum size of array and size represents the queue size.
2. Initialize Capacity = MaxSize of Array, QSize=0, Front =0, Rear =
-1.
34
3. Enqueue : To insert an element into the queue:
a. If Capacity = Qsize, queue is full and insertion is not possible.
b. Otherwise, increment Rear by 1 as follows
if (++Rear == Capacity)
Rear = 0;
That is after incrementing, if Rear reaches capacity, wrap it to zero since
here queue is implemented as circular queue.
c. Insert the element at rear position as follows.
Array[Rear] = element

3. Dequeue : To delete an element from the queue:


a. If Qsize=0, queue is empty and deletion is not possible.
b. Otherwise, increment Front by 1 as follows
if (++Front == Capacity)
Front = 0;
That is after incrementing, if Front reaches capacity, wrap it to zero since
here queue is implemented as circular queue.
4. To view the content of queue, display array content front Front position to
Rear position. When index is reaching end of array but rear is not reached means,
index also should be wrapped to zero.
Program

35
Viva Questions

1. What is the difference between stack and queue?


2. What are all the basic operations in queue?
3. List out the applications of queue.
4. How circular queue is efficient compared to linear queue?
5. What is meant be deque (double ended queue)?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result
Thus the program for array implementation of queue(circular) is done.
Ex .No 6a Linked List Implementation of Stack ADT
Aim
To implement stack data structure using linked list.
Why Linked List version for Stack?

36
In case of array implementation of stack, array size is fixed either at compile
time or at run time depending on whether array size is declared as static or
dynamic.
Linked list is a data structure consisting of a group of nodes which together
represent a sequence. Here we need to apply the application of linkedlist to
perform basic operations of stack like push, pop, viewtop and viewstack. The size
restricton of array version can be eliminated in linked list version of stack. But
performance wise, linked list version is slower compared to array version.

Algorithm
1. Create a structure with a data filed and pointer field (Next) that points to the
next node in the list.
2. Create a header node, S which always has to point to top node in stack. When
stack is empty S->Next = NULL.
3. To Push the data d into stack S,
i) Create a new node, called TmpNode using the malloc function. If
TmpNode is NULL, print as memory error and do exit.
ii) Assign d to data field as TmpNode->data = d.
iii) Now TmpNode will become as top node and existing top node will be
pointed by TmpNode as follows.
TmpNode->Next=S->Next;
S->Next=TmpNode.
4. To perform Pop operation,
i) If S->Next == NULL, display stack is empty.
ii) Otherwise, store the node pointed by S (top node) in FirstNode.
First Node = S->Next;
iii) Then make S to point to second node in stack as follows.
S->Next = FirstNode->Next;
iv) Now remove FirstNode from memory using free(FirstNode).
5. Toview top element,
If S->Next == NULL, display stack is empty.
Otherwise print the data in first node as S->Next->data.
6. To view elements in stack,
If S->Next == NULL, display stack is empty.
Otherwise, let Temp=S->Next, first node in stack.
1. Print Temp->data
2. Move to next node as Temp=Temp->Next.
3. Repeat from step 1 until Temp becomes NULL.
Program

37
Viva Questions

1. Is Stack fast in array or linked list version?


2. In Stack using linked list, where does push and pop take place?
3. For real time applications of stack, whether array or linked list version is
efficient? Why?
4. How is top of stack represented a header node?
5. How will you identify an empty stack?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)

38
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result
Thus the linked list version of stack is done.
Ex. No. 6b Linked List Implementation of Queue ADT
Aim
To implement Queue ADT using linked list.

Linked List Implementation of a Queue


We go for a linked list implementation of a queue rather than an array
implementation because of the run time memory allocation feature of linked lists.
There will be two pointers here. One is the Frontnode which acts as the header
node and another is the Rear node which points to last node in list.To perform
enqueue, a new node is created and attached with rear end. To perform dequeue,
Frontnode is made to point to second node in list and first node is removed from
memory.

Algorithm
1. Create a structure with a data filed and pointer field (Next) that points to the
next node in the list.
2. Create two nodes Front and Rear and make Front->Next = NULL indicating
queue is empty.
3. Enqueue: To insert an element in to queue
i) Create a new node, TmpNode
ii) If this is the first element to be inserted (Front->Next == NULL) then
attach TmpNode as first node and make TmpNode as last node.
Front->Next=TmpNode;
Rear=Front->Next;
iii) Otherwise, attach TmpNode after current Rear node and make
TmpNode is Rear node
Rear->Next=TmpNode;
Rear=Rear->Next;
4. Dequeue:To delete an element from queue
i) If Front->Next = NULL, display queue as empty.
ii) Otherwise,
a) Connect Front node with second node
b) Free the first node
c) If queue becomes empty make Rear node to be Front Node
FirstNode = Front->Next;
39
Front->Next = FirstNode->Next;
free(FirstNode);
if(Front->Next==NULL)
=Front;

5. To display the content of queue


i)If Front->Next == NULL, display queue is empty.
ii) Otherwise, let Temp=Front->Next, first node in queue.
iii) Print Temp->data
iv)Move to next node as Temp=Temp->Next.
v)Repeat from step iii) until Temp becomes NULL.

Program

Viva Questions

1. What is the significance of front and rear nodes?


2. Where do the operations of queue take place in terms of front and rear node?
3. Are queue operations efficient in Array or Linked list implementation?
4. How does an empty queue identified?
40
5. What is the time complexity of enqueue and dequeue operation in linked list
version?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result
Thus the program for linked list implementation of queue is done.
Ex. No. 7 Applications of Stack
7a. Checking balanced braces in expression
Aim
To check whether an expression is balanced in terms of braces using array
implementation of stack.
Theory
Compilers check our programs for syntax errors, but frequently a lack of one
symbol will cause the compiler to spill out a hundred lines of diagnostics without
identifying the real error. Thus, every right curly brace }, square brace ] and
parentheses ) must correspond to its left counterpart {, [, ( respectively in
addition to count matching in number of open and closed braces. This can be
verified using a stack.

Algorithm
1. Create an empty stack implemented using array version.
2. Get the expression to be checked for balanced braces in a string str.
3. Scan the expression from left to right, character by character.
4. During your scanning, for every character in str at the position pos
a. If str[pos] = { or [ or ( parentheses push it into the stack.
b. If str[pos] is a right brace, check stack.
i) If stack is empty, no equivalent open brace is found stack. So print
expression is not balanced and do exit.
ii) Otherwise, check top of stack. If corresponding open brace is found
perform a pop.

41
5. When the end of the expression is reached, the stack must be empty. Otherwise
one ormore left braces has been opened and not closed. So print expression is not
balanced and do exit.
Program

Ex. No. 7b Evaluation of postfix expression


Aim:
To evaluate a postfix expression using array implementation of stack.
Theory:
Postfix notation / Reverse Polish Notation is a way of writing algebraic
expressions without the use of parentheses or rules of operator precedence. The
42
expression (A+B)/(CD) would be written as AB+CD-/ in postfix notation.
Evaluating an expression in postfix notation is trivially easy if you use a stack.
The postfix expression to be evaluated is scanned from left to right. Variables or
constants are pushed onto the stack. When an operator is encountered, the
indicated action is performed using the top elements of the stack, and the result
replaces the operands on the stack.

Algorithm:
1. Create an empty stack implemented using array version.
2. Get the expression in postfix form to be evaluated in a string str.
3. Scan the expression from left to right, character by character.
4. During your scanning, for every character in str at the position pos
a. If str[pos] == operand, push it on to the stack and continue scanning.
b. If str[pos] == any operator op
i) pop the topmost element and keep in var2 and pos next top element
and
keep in var1 from the stack,
ii) Apply the operator as var1 op var2 push the result back to the stack.
5. When end of the string is reached, there will be only one element in the stack
which is the final result of evaluating the expression.
6. Pop this value and print it as a result of postfix expression.
Program

43
Ex. No. 7c Conversion of Infix to Postfix expression
Aim
To convert infix to postfix expression using array implementation of stack.

Theory
Conventional notation is called infix notation. The arithmetic operators
appear between two operands. Parentheses are required to specify the order of
the operations. For example: a + (b * c).Post fix notation eliminates the need for
parentheses. There are no precedence rules to learn, and parentheses are never
needed. Because of this simplicity, some popular hand-held calculators use
postfix notation to avoid the complications of multiple sets of parentheses. The
operator is placed directly after the two operands it needs to apply. For example:
a b c * +. To convert infix expression to postfix for, stack can be very well used.

Algorithm
1. Create an empty stack implemented using array version.
2. Get the expression in infix form in a string str.
3. Scan the expression from left to right, character by character.
4. During your scanning, for every character in str at the position pos
i) If str[pos] is an operand, print it.
ii) If str[pos]== (, push it in stack.
iii) if str[pos] == ), pop and print symbols until you pop a ( from a stack.
iv) If str[pos] == +, check the top of stack. If top of the stack is +, -, *, /
(equal or higher priority), pop and print symbols. Then push +.
v) If str[pos]== - (minus), apply similar to above step.
vi) If str[pos]== *, check top of stack for *, /. If so, pop and print symbols
and then push *. Otherwise print *.
vi) Above step is applicable for / (division) also.
5. Once you reach end of expression, pop the entire stack and print the symbols.

44
Program

45
Viva Questions

1. Explain the checking balanced parenthesis using stack?


2. Explain infix expression into postfix expression using stack
3. Explain postfix evaluation using stack?
4. Which implementation (Array / Linked list) is more suitable for these
applications?
5. What are the other applications of stack?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result
Thus the programs to check balanced parenthesis, evaluating postfix
expression and converting infix expression to postfix using stack are done.

Ex. No. 8 Implementation of Binary Search Trees

Aim: To implement binary search trees using linked lists.

Binary Search Trees:

A binary tree is a tree in which no node can have more than two children. In
a binary search tree ,for every node, X, in the tree, the values of all the keys in its
left sub tree are smaller than the key value of X, and the values of all the keys in
its right sub tree are larger than the key value of X. The time taken for basic
operations on a binary search tree is proportional to the height of the tree.

46
In the linked list implementation of binary search trees, each element is
represented by node with two link fields and a data field. Each connecting line (or
edge) in a binary tree will be represented by a link field. A leaf node has a
leftChild and rightChild link of NULL value. Root node will be pointed to by a
pointer variable.

Algorithm:

1. Create a structure with a data field and two pointer fields Left and Right that
points to the left and right child node respectively in the tree.

2. Let node T serves as root node.

3. To insert a new data X into the tree:

a. If T== NULL,

i) Cretea a new node T and allocate memory for it

ii) T->data= X

iii) T->Left = NULL; T->Right = NULL;

b. Otherwise

i) If X < T->data, move to left subtree as

T=T->Left;

Repeat Step 3 with left subtree

ii) Else if X > T->data, move to right subtree as

T = T->Right; Repeat Step 3 with left subtree

iii) Else print Element exists in Tree.


47
4. To delete an element X from the tree:

a. Find the node where the element resides.

b. If the node has no left and right children, then the pointer to that node
from the parent is changed to NULL and the node is freed from memory.

c. If the node has only one child, then its parent is made to point to its one
child and node is freed.

d. If the node has both left and right children:


i. Look at the right subtree rooted at the right child ofthe node).
ii. Find the Minimum in that right subtree.
iii. Replace the key of the node to be deleted by this minimum
element.
iv. Delete the node containing this minimum element from right
subtree.
5. To find an element X in the tree with root node T:
a. If T is NULL, print Tree is empty.
b. If X < T->data,
T =T->Left. // move to left subtree and continue searching
Repeat Step 5
c. If X > T->data,
T =T->Right. // move to left subtree and continue searching
Repeat Step 5

d. Else print that data is found / return T containing data to be found.

6. To find the minimum element in a tree with root node T:

a. If T is NULL return NULL.

b. Otherwise slide T to T->Left until T->Left becomes NULL.

c. Return the value at T.

7. To find the maximum element in a tree with root node T:

a. If T is NULL return NULL.

b. Otherwise slide T to T->Right until T->Right becomes NULL.

c. Return the value at T.

Program

48
49
Viva Questions

1. What are the applications of trees and binary search trees?


2. Give the tree traversals for given tree.
3. Why it is said that searching a node in a binary search tree is efficient than in
simple binary tree?
4. Give the meaning of following terms : Leaf, Sibling, depth, height, degree
5. How is searching efficient in BST compared to linear data structures?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result
Thus the program for binary search tree implementation is done
Ex. No. 9a Heap Sort
Aim
To sort a series of numbers using the heap sort method
Heap Sort:
A sorting algorithm that works by first organizing the data to be sorted into a
special type of binary tree called a heap. The heap itself has, by definition, the

50
largest value at the top of the tree, so the heap sort algorithm must also reverse
the order. It does this with the following steps:

1. Remove the topmost item (the largest) and replace it with the rightmost
leaf. The topmost item is stored in an array.

2. Re-establish the heap.

3. Repeat steps 1 and 2 until there are no more items left in the heap.

The heap sort works as it name suggests - it begins by building a heap out
of the data set, and then removing the largest item and placing it at the end of
the sorted array. After removing the largest item, it reconstructs the heap and
removes the largest remaining item and places it in the next open position from
the end of the sorted array. This is repeated until there are no items left in the
heap and the sorted array is full. Elementary implementations require two arrays -
one to hold the heap and the other to hold the sorted elements.
Algorithm
1. Build a heap out of the data set.
2. Remove the largest item and place it at the end of the sorted array.
3. After removing the largest item, reconstruct heap and remove largest
remaining
item and place it in the next open position from the end of the sorted array.
4. Step (3) is repeated until there are no items left in the heap and the sorted
array is full.
5. Implementations require two arrays - one to hold the heap and the other to
hold the sorted elements.

Ex. No. 9b Quick Sort


Aim
To sort a series of numbers using the quick sort method.
Quick Sort
The quick sort is an in-place, divide-and-conquer, massively recursive sort.
Infact, quick sort algorithm is simple in theory, but difficult to put into code.
Quick sort normally does not perform well for small arrays.
The recursive algorithm consists of four steps:

51
1. If there are one or less element in the array to be sorted, return
immediately.

2. Pick an element in the array to serve as a "pivot" point. (Usually the left-
most element inthe array is used as pivot.)

3. Split the array into two parts - one with elements larger than the pivot and
the other withelements smaller than the pivot.

4. Recursively repeat the algorithm for both halves of the original array.

5. The quick sort is by far the fastest of the common sorting algorithms.

Algorithm:
1. Get N elements which are to be sorted, and store it in the array A.
2. Select the element from A[0] to A[N-1] for middle. This element is the pivot.
3. Partition the remaining elements into segments left and right so that no
element inleft has a key larger than that of the pivot and no element in right has a
key smaller thanthat of the pivot.
4. Sort left using quick sort recursively.
5. Sort right using quick sort recursively.
6. Display the sorted array A.

Programs :

52
Viva Questions
53
1. What is meant by internal and external sorting?
2. What is time complexity of various sorting techniqies?
3. Which sorting is efficient for less number of elements and which is efficient for
very high number of elelemts?
4. Which sorting will be better when elements are almost in sorted order?
5. What is meant by divide and conquer strategy in sorting?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result

Thus the program for heap sort and quick sort is done.

Ex. No 10a Linear Searching

Aim

To search the presence of an element in given array

Searching

A search algorithm is an algorithm for finding an item with specified


properties among a collection of items. Sequential algorithms dont make any
assumptions about the order of the list. It justcompares the element to be found
with every value in the list sequentially one after another.

Program

54
Ex. No 10b Binary Searching

Aim

To search the presence of an element in given array

Binary Search

This searching assumes that the list is already in order. Based on the value
to be searched, the search space is halved every time till the value is found

Algorithm

Procedure binary_search
A sorted array
n size of array
x value to be searched

Set lowerBound = 1
Set upperBound = n

while x not found


if upperBound < lowerBound
EXIT: x does not exists.

set midPoint = lowerBound + ( upperBound - lowerBound ) / 2


55
if A[midPoint] < x
set lowerBound = midPoint + 1

if A[midPoint] > x
set upperBound = midPoint - 1

if A[midPoint] = x
EXIT: x found at location midPoint
end while
end procedure

Program

Viva Questions

1. What is meant by searching?


2. What are the applications for searching?
3. What are the types of searching algorithms?
4. What is the precondition for binary search?
56
5. What is the time complexity for linear and binary search algorithsm?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result

Thus the programs to perform binary search in a sorted array and linear search in
an array are done.

Ex. No 11 Dijikstras shortest path algorithm

Aim

To Implement Disjikstra shortest path algorithms for graphs

Dijikstras Algorithm

It provides a solution to the single-source shortest path problem. It Works on


both directed and undirected graphs. However, all edges must have nonnegative
weights.In unweighted graphs, edge cost can be considered as 1. The basic
algorithm concept is to create a table of information about the currently known
best way to reach each vertex (distance, previous vertex) and improve it until it
reaches the best solution.

Algorithm

Let s be the source vertex and initial current vertex


Set ds = 0, ps = null , known = True
// d shortest distance from source node s,
//p previous node
//known indicates that shortest path to that node is found.
3. For all other vertices v V, v r, set dv = , pv = null, known = False
4. For every vertex w adjacent to current vertex v and also unknown, update the
weight of the shortest path connecting source s to w through v as follows:
dw= min (dw, dv + Cv,w)
where Cv,w is the cost of the edge (v,w).
57
If minimum is dv + Cv,w update pw = v
5. From the unknown vertices, pick the vertex with minimum distance and make it
as the current vertex.
6. Repeat steps 4 & 5 until shortest paths to all vertices are found.

Pseudo Code

function Dijkstra(Graph, source)


{
dist[source] := 0 // Distance from source to source
for each vertex v source in Graph: // Initializations
{
dist[v] := infinity
previous[v] := undefined
known[v]=false;
}
while there are unknown vertices
{
v:=unknown vertex with min dist[u]//src in first case
known[v]= TRUE;
for each unknown neighbor, w of v
{
alt := dist[v] + C(v, w)
if alt < dist[w]
{
dist[w] := alt
previous[w] := v
}
}
}
return dist[ ], previous [ ]
}

Program

58
59
Viva Questions

1. State the applications of shortest path algorithms?


2. What is meant by traveling salesman problem?
3. What are the types of shortest path algorithms?
4. What is meant by single source shortest path problem?
5. What is meant by all source shortest path problem?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

60
Result

Thus the program for implementing Dijkstra shortest path algorithm is done.

Ex. No 12 Minimum Spanning Tree algorithms

12.a Kruskals Algorithm

Aim

To implement krsukals algorithm to find the minimum spanning tree for a given
graph

Theory

A minimum spanning tree of an undirected graph G is a tree formed from


graph edges that connects all the vertices of G at lowest total cost. A minimum
spanning tree exists if and only if G is connected. let G=(V,E) be a connected,
undirected graph. For each edge (u, v) in E, we have a weight Cu,v specifying the
cost (length of edge) to connect u and v. Our problem is find an acyclic subset T
of E that connects all of the vertices in V and whose total weight is minimized.

61
Graph G

Gs
minimum
spanning
tree

Kruskal Algorithm

Kruskal's algorithm is a greedy algorithm in graph theory that finds a


minimum spanning tree for a connected weighted graph. It finds a subset of the
edges that forms a tree that includes every vertex, where the total weight of all
62
the edges in the tree is minimized. It first sorts edges by increasing edge weight
and then selects first |V| 1 edges that do not generate a cycle.

Steps

1. Get the number of vertices and cost adjacency matrix as input of a graph
2. T (the final spanning tree) is defined to be the empty set;
3. For each vertex v of G, make the empty set out of v;
4. Sort the edges of G in ascending (non-decreasing) order;
5. For each edge (u, v) from the sorted list of step 4.
6. If u and v belong to different sets
7. Add (u,v) to T;
8. Get together u and v in one single set;
9. Return T

Program

63
64
12 b Prims Algorithm

Aim

To implement prims algorithm to find out minimum cost spanning tree for given
graph

Prims Algorithm

1. Get the number of vertices and cost adjacency matrix of a graph.

2. Pick any vertex r to be a root and let it be current vertex.

3. Set dr = 0, pr = null , known = True


d shortest distance from so far constructed tree,
p previous node
known indicates that the node is added to MST
4. For all other vertices v V, v r, set dv = , pv = null, known = False
5. For every vertex w adjacent to current vertex v and also unknown, update the
weight of the shortest path connecting root to w through v as follows :
dw= min (dw, Cv,w)
where Cv,w is the cost of the edge (v,w).
If minimum is Cv,w update pw = v
6. From the unknown vertices, pick the vertex with minimum distance and make
it as the current vertex.
7. Repeat steps 5 & 6 until all vertices becomes known
Program

65
66
Viva Questions

1. State the practical applications of minimum spanning tree


2. What is meant by spanning tree?
3. What is meant by spanning tree?
4. What is the rationale behind kruskal algorithm?
5. Will either Prim or Kruskal algorithm work with negative edges?

Evaluation

Assessment Marks
Scored
Understanding Problem statement (10)
Efficiency of understanding algorithm (15)
Efficiency of program (40)
Output (15)
Viva (20)
(Technical 10 and Communications - 10)
Total (100)

Result

Thus the programs for implementing the minimum spanning tree algorithms are
done.

67

Vous aimerez peut-être aussi