Lab Manual FEB 9
Lab Manual FEB 9
Data Structures
Student Name : .
Register Number : .
Section :
..
1
TABLE OF CONTENTS
1 Bonafide Certificate 3
3 Course Plan 5
4 Introduction 11
Experiments
5 Simple C Programs 12
11 Applications of stack 46
13 Sorting Technique0073 58
14 Searching Techniques 62
Anand Nagar,Krishnankoil-626126
2
Srivilliputtur(via),Virudhunagar(Dt),Tamil Nadu
BONAFIDE CERTIFICATE
________________________________
____________
REGISTER NUMBER
Name: Reg No :
3
Class : Faculty :
Marks Faculty
S.No Date Experiment
(100) Signature
1 Simple C Programs
7 Applications of stack
9 Sorting Techniques
10 Searching Techniques
COURSE PLAN
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
COURSE OBJECTIVE:
DESCRIPTION
PSOs
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
6
Design and Implement the linear and non-linear data structure and
CO2 its operations
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
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
WEB RESOURCES:
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
INTRODUCTION
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.
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.
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
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
Aim
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:
Pointers:
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:
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.
Algorithm
18
Programs
19
20
21
Viva Questions
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.
Aim
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.
10 20 30 40
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
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 ++;
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
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.
They are a dynamic in nature which allocates the memory when required.
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
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
Program
32
Viva Questions
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
35
Viva Questions
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
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.
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;
Program
Viva Questions
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
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
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.
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.
a. If T== NULL,
ii) T->data= X
b. Otherwise
T=T->Left;
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.
Program
48
49
Viva Questions
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.
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.
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.
Aim
Searching
Program
54
Ex. No 10b Binary Searching
Aim
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
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
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.
Aim
Dijikstras Algorithm
Algorithm
Pseudo Code
Program
58
59
Viva Questions
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.
Aim
To implement krsukals algorithm to find the minimum spanning tree for a given
graph
Theory
61
Graph G
Gs
minimum
spanning
tree
Kruskal Algorithm
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
65
66
Viva Questions
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