0% found this document useful (0 votes)
6 views

DS

The document is a laboratory manual for the Data Structure Lab (BCS 351) at JSS Academy of Technical Education, outlining the vision and mission of the institute and department, as well as the program educational outcomes and specific course outcomes. It includes a list of experiments related to sorting and searching algorithms, data structures, and guidelines for laboratory conduct and record preparation. The manual aims to equip students with practical skills in implementing data structures and algorithms using programming languages, particularly C.

Uploaded by

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

DS

The document is a laboratory manual for the Data Structure Lab (BCS 351) at JSS Academy of Technical Education, outlining the vision and mission of the institute and department, as well as the program educational outcomes and specific course outcomes. It includes a list of experiments related to sorting and searching algorithms, data structures, and guidelines for laboratory conduct and record preparation. The manual aims to equip students with practical skills in implementing data structures and algorithms using programming languages, particularly C.

Uploaded by

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

JSS MAHAVIDYAPEETHA

LABORATORY MANUAL

Subject Name: Data Structure Lab


Subject Code: BCS 351

COURSE: B.Tech. SEMESTER: III SEM


Name

Roll No.

Section-Batch

Department of Computer Science and Engineering


JSS ACADEMY OF TECHNICAL EDUCATION
C-20/1, SECTOR-62, NOIDA
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

VISION OF THE INSTITUTE


JSS Academy of Technical Education, Noida aims to become an Institution of excellence in
imparting quality Outcome Based Education that empowers the young generation with Knowledge,
Skills, Research, Aptitude and Ethical values to solve Contemporary Challenging Problems.

MISSION OF THE INSTITUTE

 Develop a platform for achieving globally acceptable level of intellectual acumen and
technological competence.

 Create an inspiring ambience that raises the motivation level for conducting quality research.

 Provide an environment for acquiring ethical values and positive attitude.

VISION OF THE DEPARTMENT

To spark the imagination of the Computer Science Engineers with values, skills and creativity to
solve the real world problems.

MISSION OF THE DEPARTMENT

 To inculcate creative thinking and problem solving skills through effective teaching, learning
and research.
 To empower professionals with core competency in the field of Computer Science and
Engineering.
 To foster independent and lifelong learning with ethical and social responsibilities.

PROGRAM EDUCATIONAL OUTCOMES (PEOs)


PEO1: To apply computational skills necessary to analyze, formulate and solve engineering problems.

PEO2: To establish as entrepreneurs, and work in interdisciplinary research and development organizations
as an individual or in a team.
PEO3: To inculcate ethical values and leadership qualities in students to have a successful career.
PEO4: To develop analytical thinking that helps them to comprehend and solve real-world problems
and inherit the attitude of lifelong learning for pursuing higher education.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 6
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

PROGRAM OUTCOMES (POs)

Engineering Graduates will be able to:

Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.

Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.

Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for
the public health and safety, and the cultural, societal, and environmental considerations.

Conduct investigations of complex problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.

The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.

Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.

Communication: Communicate effectively on complex engineering activities with the engineering


community and with society at large, such as, being able to comprehend and

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 6
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team,
to manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 6
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO1: Acquiring in-depth knowledge of theoretical foundations and issues in Computer


Science to induce learning abilities for developing computational skills.

PSO2: Ability to analyse, design, develop, test and manage complex software system and
applications using advanced tools and techniques.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 6
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

COURSE OUTCOMES (COs)


Students be capable to identity the appropriate data structure for given problem
C209.1
Students will be able to understand various data structure such as stacks, queues, trees,
C209.2 graphs, etc. to solve various computing problems.
Students will be able to implement various kinds of searching and sorting techniques, and
C209.3 know when to choose which techniques.
Students will be able to learn implementation different operations on BST.
C209.4

CO-PO MAPPING
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

3 2 2 1 3 - - 1 1 1 - 2
C209.1
2 3 3 2 3 - - 1 1 1 - 2
C209.2
2 3 3 2 3 - - 1 1 1 - 2
C209.3
2 3 3 2 3 - - 1 1 1 - 2
C209.4
2.25 2.75 2.75 1.75 3.00 - - 1.00 1.00 1.00 - 2.00
C209

CO-PSO MAPPING

PSO1 PSO2
2 2
C 209.1
2 2
C 209.2
2 2
C 209.3
2 2
C 209.4
C209 2.00 2.00

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 6
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

LIST OF EXPERIMENTS

Exp. Title of the Experiment Corresponding


No. CO
A. Sorting Algorithms
Write a Program to implement Bubble Sort.
1. C 209.3
Write a Program to implement Selection Sort.
2. C 209.3
Write a Program to implement Insertion Sort.
3. C 209.3
Write a Program to implement Quick Sort.
4. C 209.3
Write a Program to implement Radix Sort.
5. C 209.3
Write a Program to implement Heap Sort.
6. C 209.3
B. Searching Algorithms and Hashing Techniques
Write a Program to implement Linear Search.
7. C 209.3
Write a Program to implement Binary Search.
8. C 209.3
Write a Program to implement BFS using linked list.
9. C 209.3
Write a Program to implement Hashing Technique.
10. C 209.3
C. Data Structures
Write a Program to implement stack using array.
11. C 209.2
Write a Program to implement queue using array.
12. C 209.2
Write a Program to implement circular queue using array.
13. C 209.2
Write a Program to implement stack using linked list.
14. C 209.2
Write a Program to implement queue using linked list.
15. C 209.2
Write a Program to implement circular queue using linked list.
16. C 209.2
Write a Program to implement binary tree using linked list.
17. C 209.2
Write a Program to implement binary search tree using linked
18. C 209.4
list.
Write a Program to implement tree traversals using linked list.
19. C 209.4

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 9
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Write a Program to implement MST (Minimum Spanning Tree).


20. C 209.1
Write a Program to implement Shortest Path algorithm.
21. C 209.1
Write a Program to convert from Infix to Prefix and Postfix
22. C 209.1
representation of an expression.
Write a Program to evaluate Prefix and Postfix expression.
23. C 209.1

Content Beyond Syllabus

24. Write a Program to solve Tower of Hanoi Problem. C 209.1

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 9
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

INTRODUCTION

In computer science, data structure is a particular way of organizing and storing data in a computer
so that it can be accessed and modified efficiently. Precisely, it is a collection of data values, the
relationships among them, and the functions or operations that can be applied to the data.

Data structures can implement one or more particular abstract data types (ADT), which specify the
operations that can be performed on a data structure and the computational complexity of those
operations. Usually, efficient data structures are the key to designing efficient algorithms. The
implementation of a data structure usually requires writing a set of procedures that create and
manipulate instances of that structure. The efficiency of a data structure cannot be analyzed separately
from those operations.

There are numerous types of data structures, generally built upon simpler primitive data types:

An array is a number of elements in a specific order, typically all of the same type. Elements are
accessed using an integer index to specify which element is required. Typical implementations
allocate contiguous memory words for the elements of arrays (but this is not always a necessity).
Arrays may be fixed-length or resizable.

A linked list is a linear collection of data elements of any type, called nodes, where each node has
itself a value, and points to the next node in the linked list. The principal advantage of a linked list
over an array is that values can always be efficiently inserted and removed without relocating the rest
of the list. Certain other operations, such as random access to a certain element, are however slower
on lists than on arrays.

Data structures are generally based on the ability of a computer to fetch and store data at any place in
its memory, specified by a pointer—a bit string, representing a memory address, that can be itself
stored in memory and manipulated by the program. Thus, the array data structures are based on
computing the addresses of data items with arithmetic operations; while the linked data structures are
based on storing addresses of data items within the structure itself.

A data structure is said to be linear if its elements form a sequence or a linear list. The linear data
structures like an array, stacks, queues and linked lists organize data in linear order.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 9
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

A data structure is said to be non-linear if its elements form a hierarchical classification where, data
items appear at various levels. Trees and Graphs are widely used non-linear data structures. Tree and
graph structures represent hierarchical relationship between individual data elements. Graphs are
nothing but trees with certain restrictions removed.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 13
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

PREFACE

In order to develop efficient software systems, it is essential that efficient algorithms and appropriate
data structures are used. The purpose of this laboratory manual is to introduce undergraduate students
to techniques for developing efficient data structures and algorithms in a systematic manner. The
manual serves as a guide for learning and implementing the linear and non- linear data structures in
a programming language (C). It basically focuses on memory management and various other
operations on data with algorithm analysis and design. The manual contains procedures, and pre-
experiment questions to help students prepare for experiments.

This practical lab manual will be helpful for students of Computer Science & Engineering for
understanding the course from the point of view of applied aspects. Though all the efforts have been
made to make this manual error free, yet some errors might have crept in inadvertently. Suggestions
from the readers for the improvement of the manual are most welcomed.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 13
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

DO’S AND DONT’S

DO’s

1. Conform to the academic discipline of the department.


2. Enter your credentials in the laboratory attendance register.
3. Read and understand how to carry out an activity thoroughly before coming to the
laboratory.
4. Ensure the uniqueness with respect to the methodology adopted for carrying out the
experiments.
5. Shut down the machine once you are done using it.

DONT’S

1. Eatables are not allowed in the laboratory.


2. Usage of mobile phones is strictly prohibited.
3. Do not open the system unit casing.
4. Do not remove anything from the computer laboratory without permission.
5. Do not touch, connect or disconnect any plug or cable without your faculty/laboratory
technician’s permission.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 13
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

GENERAL SAFETY INSTRUCTIONS

1. Know the location of the fire extinguisher and the first aid box and how to use them in case
of an emergency.
2. Report fires or accidents to your faculty /laboratory technician immediately.
3. Report any broken plugs or exposed electrical wires to your faculty/laboratory
technician immediately.

4. Do not plug in external devices without scanning them for computer viruses.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 13
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

DETAILS OF THE EXPERIMENTS CONDUCTED


(TO BE USED BY THE STUDENTS IN THEIR RECORDS)

MARKS FACULTY
DATE OF EXPT. TITLE OF THE PAGE
S.No AWARDED SIGNATURE
CONDUCTION No EXPERIMENT No.
(20) WITH REMARK

10

11

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 16
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

12

13

14

15

16

17

18

19

20

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 16
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

GUIDELINES FOR LABORTORY RECORD PREPARATION

While preparing the lab records, the student is required to adhere to the following guidelines:
Contents to be included in Lab Records:
1. Cover page
2. Vision
3. Mission
4. PEOs
5. POs
6. PSOs
7. COs
8. CO-PO-PSO mapping
9. Index
10. Experiments
 Aim
 Source code
 Input-Output
A separate copy needs to be maintained for pre-lab written work
The student is required to make the Lab File as per the format given on the next two pages.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 16
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

JSS ACADEMY OF TECHNICAL EDUCATION


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Subject - DATA STRUCTURE LAB FILE

Name

Roll No.

Section- Batch

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

INDEX

Expt. Experiment Name Date of Date of Faculty


No. Conduction Submission Signature

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

GUIDELINES FOR ASSESSMENT

Students are provided with the details of the experiment (Aim, pre-experimental questions, procedure
etc.) to be conducted in next lab and are expected to come prepared for each lab class.
Faculty ensures that students have completed the required pre-experiment questions and they
complete the in-lab programming assignment(s) before the end of class. Given that the lab programs
are meant to be formative in nature, students can ask faculty for help before and during the lab class.
Student’s performance will be assessed in each lab based on the following Lab Assessment
Components:
AC1: Written Work (Max. marks = 4)
AC2: Fundamental Knowledge to conduct Experiment (Max. marks = 4)
AC3: Experiment Completed Successfully (Max. marks = 4)
AC4: Questions Answered (Max. marks = 4)
AC5: Punctuality (Max. marks = 4)

In each lab class, students will be awarded marks out of 4 under each component head, making it
total out of 20 marks.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 1

Aim: To Implement Bubble Sort.

Description: Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison based
algorithm in which each pair of adjacent elements is compared and elements are swapped if they are
not in order. This algorithm is not suitable for large data sets as its average and worst case complexity
are of O(n2) where n are no. of items.

This is a in-place comparison based sorting algorithm. Here, a sub-list is maintained which is always
sorted. For example, the lower part of an array is maintained to be sorted. A element which is to be
inserted in this sorted sub-list, has to find its appropriate place and insert it there. Hence the name
insertion sort. The array is searched sequentially and unsorted items are moved and inserted into
sorted sub-list (in the same array). This algorithm is not suitable for large data sets as its average and
worst case complexity are of Ο (n2) where n are no. of items. This process goes until all the
unsorted values are covered in sorted sub-list.

Pre Experiment Questions:


Q1. What is the difference between stable sort and unstable sort?
Q2. List out the stable sorting algorithms.
Q3. List out the unstable sorting algorithms.
Q4. What is the advantage of bubble sort over other sorting techniques?

Algorithm for Bubble Sort:

We assume list is an array of n elements. We further assume that swap function, swaps the values of
given array elements.
begin BubbleSort(list)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Input:
157289

Output:
Sorted Elements: 1 2 5 7 8 9

Post Experiment Questions:

Q1. What is an internal sorting algorithm?


Q2. What is an external sorting algorithm?
Q3. What is the worst case complexity of bubble sort?
Q4. The given array is arr = {1,2,4,3}. Bubble sort is used to sort the array elements. How many
iterations will be done to sort the array?

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 2

Aim: To Implement Selection Sort.

Description: Selection sort is a simple sorting algorithm. This sorting algorithm is a in-place
comparison based algorithm in which the list is divided into two parts, sorted part at left end and
unsorted part at right end. Initially sorted part is empty and unsorted part is entire list. Smallest
element is selected from the unsorted array and swapped with the leftmost element and that element
becomes part of sorted array. This process continues moving unsorted array boundary by one
element to the right. This algorithm is not suitable for large data sets as its average and worst case
complexity are of O(n2) where n are no. of items.

Pre Experiment Questions:

Q1.What is the difference between internal sorting and external sorting?


Q2. What do you mean by in-place sorting?
Q3. In the following scenarios, when will you use selection sort?
a) The input is already sorted
b) A large file has to be sorted
c) Large values need to be sorted with small keys
d) Small values need to be sorted with large keys
Q4. What is the worst case complexity of selection sort?

Algorithm for Selection sort :

Step 1 − Set MIN to location 0


Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted

Input:
136289

Output:
Sorted Elements: 1 2 3 6 8 9

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Post Experiment Questions:

Q1. What is the advantage of selection sort over other sorting techniques?
a) It requires no additional storage space
b) It is scalable
c) It works best for inputs which are already sorted
d) It is faster than any other sorting technique

Q2. What is the average case complexity of selection sort?


Q3. What is the disadvantage of selection sort?
Q4. The given array is arr = {3,4,5,2,1}. The number of iterations in bubble sort and selection sort
respectively are,
a) 5 and 4
b) 4 and 5
c) 2 and 4
d) 2 and 5

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 3

Aim: To Implement Insertion Sort.


Description: Insertion sort is based on the idea that one element from the input elements is
consumed in each iteration to find its correct position i.e the position to which it belongs in a
sorted array.
It iterates the input elements by growing the sorted array at each iteration. It compares the
current element with the largest value in the sorted array. If the current element is greater,
then it leaves the element in its place and moves on to the next element else it finds its
correct position in the sorted array and moves it to that position. This is done by shifting all
the elements, which are larger than the current element, in the sorted array to one position
ahead

Pre-Experiment Question:

Q1. Which is the correct order of the following algorithms with respect to their time
Complexity in the best case?
a) Merge sort > Quick sort >Insertion sort > selection sort
b) insertion sort < Quick sort < Merge sort < selection sort
c) Merge sort > selection sort > quick sort > insertion sort
d) Merge sort > Quick sort > selection sort > insertion sort

Q2. Consider the array A[]= {6,4,8,1,3} apply the insertion sort to sort the array . Consider the
cost associated with each sort is 25 rupees , what is the total cost of the insertion sort when
element 1 reaches the first position of the array ?
a) 50
b) 25
c) 75
d) 100

Algorithm for Insertion sort:


Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the value to be
sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Input:
136259

Output:
Sorted Elements: 1 2 3 5 6 9

PostExperiment Question:

Q1. Consider an array of elements arr[5]= {5,4,3,2,1} , what are the steps of insertions done while
doing insertion sort in the array.
a) 4 5 3 2 1 3 4 5 2 1 2 3 4 5 1 1 2 3 4 5

b) 5 4 3 1 2 5 4 1 2 3 5 1 2 3 4 1 2 3 4 5
c) 4 3 2 1 5 3 2 1 5 4 2 1 5 4 3 1 5 4 3 2
d) 4 5 3 2 1 2 3 4 5 1 3 4 5 2 1 1 2 3 4 5

Q2. Which sorting algorithm will take least time when all elements of input array are
identical? Consider typical implementations of sorting algorithms.
a)Insertion Sort
b)Heap Sort
c) Merge Sort
d) Selection Sort
Q3. If all the elements in an input array is equal for example {1,1,1,1,1,1}, What would be the
running time of the Insertion Algorithm?
Q4. What operation does the Insertion Sort use to move numbers from the unsorted section to the
sorted section of the list?
a) Finding the minimum value
b) Swapping
c) Finding out an pivot value
d) None of the above

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 4

Aim: To Implement Quick Sort.

Description: QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and
partitions the given array around the picked pivot. There are many different versions of quickSort
that pick pivot in different ways.

1. Always pick first element as pivot.


2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.
The key process in quickSort is partition(). Target of partitions is, given an array and an element x
of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller
than x) before x, and put all greater elements (greater than x) after x.

Pre Experimental Question:

Q1. Suppose we are sorting an array of eight integers using quicksort, and we have just finished the
first partitioning with the array looking like this:
2 5 1 7 9 12 11 10
Which statement is correct?
(A) The pivot could be either the 7 or the 9.
(B) The pivot could be the 7, but it is not the 9
(C) The pivot is not the 7, but it could be the 9
(D) Neither the 7 nor the 9 is the pivot.

Q2. What is the time complexity of Quick sort in Worst case?

Algorithm for Quick sort:

quickSort(arr[], low, high)


{

if (low < high)


{
/* pi is partitioning index, arr[pi] is now

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

at right place */
pi = partition(arr, low, high);
quickSort(arr, low, pi - 1); // Before pi
quickSort(arr, pi + 1, high); // After pi
}
}

Input:
1 3 6 2 8 9 4 10

Output:
Sorted Elements: 1 2 3 4 6 8 9 10

Post Experimental Question:

Q1. Which of the following is not a stable sorting algorithm in its typical implementation.
Insertion Sort
Merge Sort
Quick Sort
Bubble Sort.

Q2. Which sorting algorithms is most efficient to sort string consisting of ASCII characters?
Quick sort
Heap sort
Merge sort
Counting sort

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 5

Aim: To Implement Radix sort.

Description: Radix Sort is a linear sorting algorithm that sorts elements by processing them digit by
digit. It is an efficient sorting algorithm for integers or strings with fixed-size keys. With worst-case
time complexity O(d * (n + b)), where d is the number of digits, n is the number of elements, and b
is the base of the number system being used.

Pre Experimental Question:

Q1. Is Radix Sort preferable to Comparison based sorting algorithms like Quick-Sort?
Q2. What is the best time complexity of the Radix sort?
a) Omega(n log(n))
b) Omega(n+k)
c) Omega(n)
d) Omega(nk)
Q3. The maximum number of comparisons needed to sort 9 items using Radix sort is
(each number is a 5 digit octal no.)
a) 45

b) 72

c) 360

d)450

Q4.Which of the following is an external sorting?


a)InsertionSort
e) BubbleSort

c)Merge Sort
d)Tree Sort

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Algorithm for Radix sort:

Step 1 − Find the largest element in the array, which is 802. It has three digits, so we will
iterate three times, once for each significant place.
Step 2 − Sort the elements based on the unit place digits (X=0). We use a stable sorting
technique, such as counting sort, to sort the digits at each significant place.
Step 3 − Sort the elements based on the tens place digits.
Step 4 − Sort the elements based on the hundreds place digits.
Step 5 − The array is now sorted in ascending order.

Input:
170 45 75 90 802 24 2 66

Output:

Sorted Element: 2 24 45 66 75 90 170 802

Post Experimental Question:

Q1.What is the time complexity of the Radix sort technique?


Q2. Given an array where numbers are in range from 1 to n6, which sorting algorithm can be used to
sort these number in linear time?
a) Not possible
b) Radix Sort
c) Counting Sort
d) Merge Sort
Q3. If there are n integers to sort, each integer has d digits and each digit is in the set {1, 2, ..., k}, radix sort can
sort the numbers in :
a) O(d n k)

b) O(d nk)

c) O((d +n) k)
d)O(d (n +k))

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 21
JSS Academy of Technical Education – NOIDA

Department of Computer Science and Engineering

EXPERIMENT - 6

Aim: To Implement Heap sort.


Description: Heap sort is a comparison based sorting technique based on Binary Heap data
structure. It is similar to selection sort where we first find the maximum element and place the
maximum element at the end. We repeat the same process for remaining element. Consider an
arrayArr which is to be sorted using Heap Sort.
 Initially build a max heap of elements in ArrArr.
 The root element, that is Arr[1]Arr[1], will contain maximum element of Arr. After that, swap
this element with the last element of ArrArr and heapify the max heap excluding the last
element which is already in its correct position and then decrease the length of heap by one.
 Repeat the step 2, until all the elements are in their correct position.

Pre-experimental Questions:
Q1. In a max-heap, element with the greatest key is always in which node?
Q2.Heap can be used as…
a)Priority queue
b)Stack
c)Adecreasingorderarray
d) None of the mentioned
Q3.What is the space complexity of searching in a heap?
Q4. What is the best case complexity in builading a heap?

Algorithm for heap sort:


void heap_sort(int Arr[ ])
{
int heap_size = N;
build_maxheap(Arr);
for(int i = N; i >= 2 ; i-- )
{
swap|(Arr[ 1 ], Arr[ i ]);
heap_size = heap_size - 1;
max_heapify(Arr, 1, heap_size);

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 30
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

}
}

Input:
1 3 6 2 8 9 4 10

Output:
Sorted Elements: 1 2 3 4 6 8 9 10

Post experimental Questions:

Q1. What is the complexity of adding an element to the heap.


Q2. The worst case complexity of deleting any arbitrary node value element from heap is…
Q3. An array consist of n elements.We want to create a heap using the elements.The time
complexity of building a heap will be in order of…………..
Q4. Given an array of element 5,7,9,1,3,10,8,4. Tick all the correct sequences of elements after
inserting all the elements in a min-heap.
a)1,3,4,7,8,9,10
b)1,4,3,8,9,5,7,10
c) 1,3,4,5,8,7,9,10
d) None of these

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 31
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 7

Aim: To Implement Linear Search.

Description: Linear search is a very simple search algorithm. In this type of search, a sequential
search is made over all items one by one. Every item is checked and if a match founds then that
particular item is returned otherwise search continues till the end of the data collection.

Pre-Experiment Questions:

Q1. Where is linear searching used?


Q2. What is the best case for linear search?
Q3. What is the worst case for linear search?
Q4.Which of the following is a disadvantage of linear search?
a) Requires more space
b) Greater time complexities compared to other searching algorithms
c)Not easy to understand
d) All of the mentioned
Algorithm for linear search

Linear Search (Array A, Value x)


Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit

Input:
157289
Elements to be found: 8
Output:
Elements found at position no. 5

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 34
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Post Experiment Questions:


Q1. Linear search is special case of which search?

Q2. What do mean by Linear search optimization?

Q3. What is the best case and worst case complexity of ordered linear search?
b) a) O(nlogn), O(logn) O(logn), O(nlogn)
c)O(n), O(1)
d)O(1), O(n)

Q4. What does the following piece of code do?

for (int i = 0; i < arr.length-1; i++)


{
for (int j = i+1; j < arr.length; j++)
{
if( (arr[i].equals(arr[j])) && (i != j) )
{
System.out.println(arr[i]);
}
}
}
a) Print the duplicate elements in the array
b) Print the element with maximum frequency
c) Print the unique elements in the array
d) None of the mentioned

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 34
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 8

Aim: To Implement Binary Search.

Description: Binary search is a fast search algorithm with run-time complexity of Ο(log n). These
search algorithms works on the principle of divide and conquer. For this algorithm to work properly
the data collection should be in sorted form. Binary search search a particular item by comparing the
middle most item of the collection. If match occurs then index of item is returned. If middle item is
greater than item then item is searched in sub-array to the right of the middle item other wise item
is search in sub-array to the left of the middle item. This process continues on sub-array as well until
the size of subarray reduces to zero.

Pre-Experiment Question:

Q1. What are the applications of binary search?


Q2. What is the worst case complexity of binary search using recursion?
Q3. What is the average case time complexity of binary search using recursion?
Q4. What is the advantage of recursive approach than an iterative approach?

Algorithm for binary search:

Procedure binary search


A ← sorted array
n ← size of array
x ← value ot 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

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

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 34
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

end while

end procedure
Input:
157289
Elements to be found: 8
Output:
Elements found at position no. 5
Post Experiment Questions:
Q1. Binary Search can be categorized into which of the following?
a) Brute Force technique
b) Divide and conquer
c) Greedy algorithm
d) Dynamic programming
Q2. What is the time complexity of binary search with iteration?
Q3. Given an array arr = {45,77,89,90,94,99,100} and key = 100; What are the mid
values(corresponding array elements) generated in the first and second iterations?
a) 90 and 99
b) 90 and 100
c) 89 and 94
d) 94 and 99
Q4. Given an array arr = {5,6,77,88,99} and key = 88; How many iterations are done until the
element is found?
a) 1
b) 3
c) 4
d) 2

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 35
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 9

Aim: To Implement BFS using linked list.


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

As in example given above, BFS algorithm traverses from A to B to E to F first then to C and G
lastly to D. It employs following rules.
Rule 1 − Visit adjacent unvisited vertex. Mark it visited. Display it. Insert it in a queue.
Rule 2 − If no adjacent vertex found, remove the first vertex from queue.
Rule 3 − Repeat Rule 1 and Rule 2 until queue is empty
Pre Experiment Questions:
Q1. What is the difference between BFS and DFS?
Q2.The Data structure used in standard implementation of Breadth First Search is?
Q3. When the Breadth First Search of a graph is unique?
Q4. Breadth First Search is equivalent to which of the traversal in the Binary Trees?
Algorithm:
Set all nodes to "not visited";

q = new Queue();

q.enqueue(initial node);

while ( q ≠ empty ) do
{
x = q.dequeue();

if ( x has not been visited )

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 37
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

visited[x] = true;

for ( every edge (x, y)

if ( y has not been visited )

q.enqueue(y);

}
}

Input:
Above mentioned graph
Output:

SABCDEFG

Post Experiment Questions:


Q1. A person wants to visit some places. He starts from a vertex and then wants to visit every
place connected to this vertex and so on. What algorithm he should use?
a) Depth First Search
b) Breadth First Search
c) Trim’s algorithm
d) None of the mentioned
Q2. The Breadth First Search traversal of a graph will result into?
a) Linked List
b) Tree
c) Graph with back edges
d) All of the mentioned
Q3. A person wants to visit some places. He starts from a vertex and then wants to visit every
place connected to this vertex and so on. What algorithm he should use?
Q4. In BFS, how many times a node is visited?

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 37
JSS Academy of Technical Education – NOIDA

EXPERIMENT - 10

Aim: To Implement Hashing Techniques.

Description: A Hash Function is a function that converts a given numeric or alphanumeric key to a small
practical integer value. The mapped integer value is used as an index in the hash table. In simple terms, a
hash function maps a significant number or string to a small integer that can be used as the index in the
hash table.

The pair is of the form (key, value), where for a given key, one can find a value using some kind of a
“function” that maps keys to values. The key for a given object can be calculated using a function called a
hash function. For example, given an array A, if i is the key, then we can find the value by simply looking
up A[i].

Pre-Experiment Questions:
h(K) = h(k x k)
Q1. A technique for direct search
Here,
k isBinary
a) the keysearch
value.

b) Linear search

c) Tree search

d) Hashing

Q2. The search techniques that takes O(1) time complexity is

a) Binary search

b) Linear search

c) Tree search

d) Hashing
(1) Division Method:

h(K) = k mod M

Here,
k is the key value, and
M is the size of the hash table.

(2) Mid Square Method:

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 38
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Input:
(1) k = 12345
M = 95

Output:

h(12345) = 12345 mod 95


= 90
Input:
(2) Suppose the hash table has 100 memory locations. So r = 2 because two digits are required to map
the key to the memory location.

k = 60

Output:

The hash value obtained is 60

k x k = 60 x 60
= 3600
h(60) = 60

Post Experiment Questions:

Q1. Key value pair is usually seen in


a) Hash Tables
b) Heaps
c) Both Hash Tables and Heaps
d) Skip Lists
Q2. What is the best definition of collision in a hash table?

a) Two entries are identical except their keys


b) Two entries with different data have the exact key
c) Two entries with different keys have the same exact hash values
d) Two entries with the exact same keys have different hash values

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 40
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 11

Aim: To Implement stack using array.

Descriptions: A stack is an abstract data type, commonly used in most programming languages Stack
ADT allows all data operations at one end only. At any given time, we can only access the top
element of a stack. This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. In
stack terminology, insertion operation is called push operation and removal operation is called
popoperation.

Stack Representation:

A stack can be implemented by means of Array (Static Implementation), and Linked list (Dynamic
implementation).

Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from
these basic stuffs, a stack is used for the following two primary operations −

push() − Pushing (storing) an element on the stack.

pop() − Removing (accessing) an element from the stack.

When data is PUSHed onto stack.

To use a stack efficiently, we need to check the status of stack as well. For the same purpose, the
following functionality is added to stacks −

peek() − get the top data element of the stack, without removing it.

isFull() − check if stack is full.

isEmpty() − check if stack is empty.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 40
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointer always
represents the top of the stack, hence named top. The top pointer provides top value of the stack
without actually removing it.

Push Operation:

The process of putting a new data element onto stack is known as a Push Operation. Push operation
involves a series of steps −

Step 1 − Checks if the stack is full.


Step 2 − If the stack is full, produces an error and exit.
Step 3 − If the stack is not full, increments top to point next empty space.
Step 4 − Adds data element to the stack location, where top is pointing.
Step 5 − Returns success.

If the linked list is used to implement the stack, then in step 3, we need to allocate space dynamically.

Pop Operation:
Accessing the content while removing it from the stack, is known as a Pop Operation. In an array
implementation of pop() operation, the data element is not actually removed, instead top is
decremented to a lower position in the stack to point to the next value. But in linked-list
implementation, pop() actually removes data element and deallocates memory space.

A Pop operation may involve the following steps −

Step 1 − Checks if the stack is empty.


Step 2 − If the stack is empty, produces an error and exit.

Data Structure Using C Lab (KCS 351) Manual (CS, III Sem) Pag e | 41
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Step 3 − If the stack is not empty, accesses the data element at which top is pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.

Pre-Experiment Questions:
Q1. Explain Stack data structures.

Q2. Which operations can be performed on the stack?

Q3. Define the underflow and overflow conditions for stack operation.

Algorithms:

Procedures to support stack functions −

Algorithm of peek() function −

begin procedure peek

return stack[top]

end procedure

Algorithm of isfull() function −

begin procedure isfull


if top equals to MAXSIZE
return true
else
return false
endif
end procedure

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 45
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Algorithm of isempty() function −

begin procedure isempty


if top less than 1
return true
else
return false
endif
end procedure
Implementation of isempty() function in C programming language is slightly different. We initialize
top at -1, as the index in array starts from 0. So we check if the top is below zero or - 1 to determine
if the stack is empty.

A simple algorithm for Push operation can be derived as follows −


begin procedure push: stack, data
if stack is full
return null
endif
top ← top + 1
stack[top] ← data
end procedure

A simple algorithm for Pop operation can be derived as follows −


begin procedure pop: stack
if stack is empty
return null
endif
data ← stack[top]
top ← top - 1
return data
end procedure

Input:

Push New Element on the Stack:


34

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 45
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Output:

34
56
21
18
TOS=3

Post Experiment Questions:

Q1. What is the advantage of dynamic implementation over static implementation of a stack?
Q2. What is the time complexity of push operation and pop operation?
Q3. Which one of the following is an application of Stack Data Structure?
a. Managing function calls
b. The stock span problem
c. Arithmetic expression evaluation
d. All of the above
Give an explanation for your answer.
Q4. Which of the following is true about linked list implementation of stack?
a. In push operation, if new nodes are inserted at the beginning of linked list, then in pop
operation, nodes must be removed from end.
b. In push operation, if new nodes are inserted at the end, then in pop operation, nodes must
be removed from the beginning.
c. Both of the above
d. None of the above
Give an explanation for your answer.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 45
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 12

Aim: To Implement queue using array

Descriptions: Queue is an abstract data structure, somewhat similar to Stack. In contrast to Queue,
queue is opened at both ends. One end is always used to insert data (enqueue) and the other is used
to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored
first will be accessed first.

Queue Representation

Same as Queue, queue can also be implemented using Array (Static Implementation), Linked-list
(Dynamic implementation)

Queue operations may involve initializing or defining the queue, utilizing it and then completing
erasing it from memory. There are two basic operations associated with queues −

enqueue() − add (store) an item to the queue.

dequeue() − remove (access) an item from the queue.

Few more functions are required to make above mentioned queue operation efficient. These are −

isfull() − checks if queue is full.

isempty() − checks if queue is empty.

In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing (or
storing) data in queue we take help of rear pointer.

There are two supportive functions of a queue –

isfull(): As we are using single dimension array to implement queue, we just check for the rear
pointer to reach at MAXSIZE to determine that queue is full. In case we maintain queue in a
circular linked-list, the algorithm will differ

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 45
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Enqueue Operation:

As queue maintains two data pointers, front and rear, its operations are comparatively more
difficult to implement than Queue.

The following steps should be taken to enqueue (insert) data into a queue −

Step 1 − Check if queue is full.


Step 2 − If queue is full, produce overflow error and exit.
Step 3 − If queue is not full, increment rear pointer to point next empty space.
Step 4 − Add data element to the queue location, where rear is pointing.
Step 5 − return success.

Sometimes, we also check that if queue is initialized or not to handle any unforeseen situations.

Dequeue Operation:
Accessing data from queue is a process of two tasks − access the data wherefront is pointing and
remove the data after access. The following steps are taken to perform dequeue operation −

Step 1 − Check if queue is empty.


Step 2 − If queue is empty, produce underflow error and exit.
Step 3 − If queue is not empty, access data where front is pointing.
Step 3 − Increment front pointer to point next available data element.
Step 5 − return success.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 48
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Pre Experiment Question:

Q1. What is the principle of a Queue data structure?

Q2. What are the overflow and underflow conditions for operations on a Queue?

Algorithms:

Algorithm of isfull() function −

begin procedure isfull

if rear equals to MAXSIZE


return true
else
return false
endif
end procedure
Algorithm of isempty() function −
begin procedure isempty
if front is less than MIN OR front is greater than rear return
true
else
return false
endif
end procedure
If value of front is less than MIN or 0, it tells that queue is not yet initialized, hence empty.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 48
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Algorithm for enqueue operation:


procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data

return true
end procedure
Algorithm for dequeue operation :
procedure dequeue
if queue is empty
return underflow
end if
data = queue[front]
front ← front + 1
return true
end procedure

For Enqueue Operation:

Input:

Enter the element 23 to be inserted in a Queue given below:

1 45 78 90

Output:

23 1 45 78 90

For Dequeue Operation:

Input:

deletion of element in a Queue given below:

23 1 45 78 90

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 48
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Output:

23 1 45 78

Post Experiment Questions

Q1. What is the advantage of dynamic implementation over static implementation of a queue?
Q2. What is the time complexity of enqueue operation and dequeue operation?
Q3. Which one of the following is an application of Queue Data Structure?
a. When a resource is shared among multiple consumers.
b. When data is transferred asynchronously (data not necessarily received at same rate as sent)
between two processes
c. Load Balancing
d. All of the above
Explain your answer.
Q4. Which of the following is true about linked list implementation of queue?
a. In push operation, if new nodes are inserted at the beginning of linked list, then in pop
operation, nodes must be removed from end.
b. In push operation, if new nodes are inserted at the end, then in pop operation, nodes must be
removed from the beginning.
c. Both of the above
d. None of the above
Explain your answer.
Q5. Suppose you are given an implementation of a queue of integers. The operations that can be
performed on the queue are:
i. isEmpty (Q) — returns true if the queue is empty, false otherwise.
ii. delete (Q) — deletes the element at the front of the queue and returns its value.
iii. insert (Q, i) — inserts the integer i at the rear of the queue.
Consider the following function:
void f (queue Q) {
int i ;
if (!isEmpty(Q)) {
i = delete(Q);
f(Q);
insert(Q, i);

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 56
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

}
}
What operation is performed by the above function f ?
a. Leaves the queue Q unchanged
b. Reverses the order of the elements in the queue Q
c. Deletes the element at the front of the queue Q and inserts it at the rear keeping the other
elements in the same order

d. Empties the queue Q

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 56
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT – 13

Aim: To Implement circular queue using array.

Descriptions: Circular queue is a linear data structure. It follows FIFO principle. In circular queue
the last node is connected back to the first node to make a circle.Circular linked list fallow the First
In First Out principle. Elements are added at the rear end and the elements are deleted at front end of
the queue.

Pre Experiments Questions:


Q1. What is the difference between queue and circular queue?
Q2. Suppose a circular queue of capacity (n – 1) elements is implemented with an array of n
elements. Assume that the insertion and deletion operation are carried out using REAR and
FRONT as array index variables, respectively. Initially, REAR = FRONT = 0. The conditions to
detect queue full and queue empty are .

Algorithm for Insert operation:

Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear
elements of the QUEUE. ITEM is the value to be inserted.
1. If (FRONT == 1 and REAR == N) or (FRONT == REAR + 1) Then
2. Print: Overflow
3. Else
4. If (REAR == 0) Then [Check if QUEUE is empty]
(a) Set FRONT = 1
(b) Set REAR = 1
5. Else If (REAR == N) Then [If REAR reaches end if QUEUE]
6. Set REAR = 1
7. Else
8. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If]
9. Set QUEUE[REAR] = ITEM

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 56
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Print: ITEM inserted [End of Step 1 If]


11. Exit

Input:
10.

Insert element 7 in a circular queue


426135

Output:
7426135

Algorithm for delete operation:


Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear elements
of the QUEUE.
1. If (FRONT == 0) Then [Check for Underflow]
2. Print: Underflow
3. Else
4.ITEM = QUEUE[FRONT]
5. If (FRONT == REAR) Then [If only element is left]
(a) Set FRONT = 0
(b)Set REAR = 0
6. Else If (FRONT == N) Then [If FRONT reaches end if QUEUE]
7. Set FRONT = 1
8. Else
9. Set FRONT = FRONT + 1 [Increment FRONT by 1] [End of Step 5 If]
10. Print: ITEM deleted [End of Step 1 If]
11.Exit

Post Experiments Questions:

Q1. What are the application areas of circular queue?


Q2. If the MAX_SIZE is the size of the array used in the implementation of circular queue. How
is rear manipulated while inserting an element in the queue?
Q3. If the MAX_SIZE is the size of the array used in the implementation of circular queue, array
index start with 0, front point to the first element in the queue, and rear point to the last element in
the queue. Which condition specify that circular queue is FULL?

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 56
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Q4. A circular queue is implemented using an array of size 10. The array index starts with 0, front
is 6, and rear is 9. The insertion of next element takes place at the array index .
Q5. If the MAX_SIZE is the size of the array used in the implementation of circular queue, array
index start with 0, front point to the first element in the queue, and rear point to the last element in
the queue. Which of the following condition specify that circular queue is EMPTY?

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 56
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT -14

Aim: To Implement stack using linked list.

Descriptions: The major problem with the stack implemented using array is, it works only for fixed
number of data values. That means the amount of data must be specified at the beginning of the
implementation itself. Stack implemented using array is not suitable, when we don't know the size of
data which we are going to use. A stack data structure can be implemented by using linked list data
structure. The stack implemented using linked list can work for unlimited number of values. That
means, stack implemented using linked list works for variable size of data. So, there is no need to fix
the size at the beginning of the implementation. The stack implemented using linked list can organize
as many as data values as we want.
In linked list implementation of a stack, every new element is inserted as 'top' element. That means
every newly inserted element is pointed by 'top'. Whenever we want to remove an element from the
stack, simply remove the node which is pointed by 'top' by moving 'top' to its next node in the list.
The next field of the first element must be always NULL.

Pre Experiment Questions:


Q1. Compare stack implementation by array and linked list.
Q2. What are the overflow and underflow conditions for different operations on stack using linked
list?
Algorithm for Inserting an element into the Stack:
Step 1: Create a newNode with given value.
Step 2: Check whether stack is Empty (top == NULL)
Step 3: If it is Empty, then set newNode → next = NULL.
Step 4: If it is Not Empty, then set newNode → next = top.
Step 5: Finally, set top = newNode.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 56
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Algorithm for Deleting an Element from a Stack:


Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display "Stack is Empty, Deletion is not possible!" and terminate the
function
Step 3: If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4: Then set 'top = top → next'.
Step 7: Finally, delete 'temp' (free(temp)).
Algorithm for Displaying stack of elements:
Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display 'Stack is Empty!' and terminate the function.
Step 3: If it is Not Empty, then define a Node pointer 'temp' and initialize with top.
Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same until
tempreaches to the
first node in the stack (temp → next != NULL).
Step 4: Finally! Display 'temp → data ---> NULL'

Input:
Insert element 7 in the stack
426135

Output:
4261357
TOS=7

Post Experiment Questions:


Q1. What is the complexity of searching for a particular element in a Singly Linked List?
Q2. Which of the following statements are correct with respect to Singly Linked List(SLL) and
Doubly Linked List(DLL)?
a. Complexity of Insertion and Deletion at known position is O(n) in SLL and O(1) in DLL
b. SLL uses lesser memory per node than DLL
c. DLL has more searching power than SLL
d. All of the mentioned
Explain your answer.
Q3. Minimum number of queues to implement stack is .

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 56
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 15

Aim: To Implement queue using linked list.

Descriptions: The major problem with the queue implemented using array is, It will work for only
fixed number of data. That means, the amount of data must be specified in the beginning itself. Queue
using array is not suitable when we don't know the size of data which we are going to use. A queue
data structure can be implemented using linked list data structure. The queue which is implemented
using linked list can work for unlimited number of values. That means, queue using linked list can
work for variable size of data (No need to fix the size at beginning of the implementation). The
Queue implemented using linked list can organize as many data values as wewant.
In linked list implementation of a queue, the last inserted node is always pointed by 'rear' and the
first node is always pointed by 'front'.

In above example, the last inserted node is 50 and it is pointed by 'rear' and the first inserted node
is 10 and it is pointed by 'front'. The order of elements inserted is 10, 15, 22 and 50.

Pre Experiment Questions:

Q1. The essential condition which is checked before insertion in a linked queue is?
Q2. The essential condition which is checked before deletion in a linked queue is?
Q3. Which of the following is true about linked list implementation of queue?
a. In push operation, if new nodes are inserted at the beginning of linked list, then in pop
operation, nodes must be removed from end
b. In push operation, if new nodes are inserted at the end, then in pop operation, nodes must be
removed from the beginning
c. Both a and b
d. None of the mentioned
Explain your answer.
Algorithm for enQueue(value) - Inserting an element into the Queue
Step 1: Create a newNode with given value and set 'newNode → next' to NULL.
Step 2: Check whether queue is Empty (rear == NULL)
Step 3: If it is Empty then, set front = newNode and rear = newNode.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 56
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Step 4: If it is Not Empty then, set rear → next = newNode and rear = newNode.
Algorithm for deQueue() - Deleting an Element from Queue
Step 1: Check whether queue is Empty (front == NULL).
Step 2: If it is Empty, then display "Queue is Empty, Deletion is not possible!" and terminate
from the function
Step 3: If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.
Step 4: Then set 'front = front → next' and delete 'temp' (free(temp)).

Algorithm for display() - Displaying the elements of Queue


Step 1: Check whether queue is Empty (front == NULL).
Step 2: If it is Empty then, display 'Queue is Empty!' and terminate the function.
Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with front.
Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same until 'temp'
reaches to 'rear' (temp → next != NULL).
Step 4: Finally! Display 'temp → data ---> NULL'.

Input:
Insert element 7 in the queue
426135
Output:
7426135

Post Experiment Questions:

Q1. What is the time complexity for insertion in linked list implementation of queue?
Q2. In linked list implementation of queue, if only front pointer is maintained, which of the
following operation take worst case linear time?
a. Insertion
b. Deletion
c. To empty a queue
d. Both a and c

Explain your answer.

Q3. In linked list implementation of a queue, front and rear pointers are tracked. Which of these
pointers will
change during an insertion into a NONEMPTY queue?

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 57
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

a. Only front pointer


b. Only rear pointer
c. Both front and rear pointer
d. None of the mentioned

Explain your answer.

Q4. In linked list implementation of a queue, front and rear pointers are tracked. Which of these
pointers will change during an insertion into EMPTY queue?
a. Only front pointer
b. Only rear pointer
c. Both front and rear pointer

d. None of the mentioned.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 61
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 16

Aim: To Implement circular queue using linked list.

Description: 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. It is also called 'Ring Buffer'. In a normal Queue, we can insert elements until
queuebecomes full.

Operations on Circular Queue:

 Front:Get the front item from queue.

 Rear: Get the last item from queue.

 enQueue(value) This function is used to insert an element into the circular queue. In a
circular queue, the new element is always inserted at Rear position.

 deQueue() This function is used to delete an element from the circular queue. In a queue,
the element is always deleted from front position.

Pre Experiment Questions:

Q1. What is circular queue?

Q2. What is the major problem with the circular queue implemented using array?

Q3. What differentiates a circular linked list from a normal linked list?

Algorithm for enQueue(value) - Inserting an element into the Queue

Step1: Create a new node dynamically and insert value into it.

Step 2: Check if front==NULL, if it is true then front = rear = (newly created node)

Step3: If it is false then rare=(newly created node) and rear node always contains the address of the
front node.

Algorithm for deQueue(value) - Deleting an element into the Queue

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 61
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Step 1: Check whether queue is empty or not means front == NULL.

Step 2: If it is empty then display Queue is empty. If queue is not empty then step 3

Step 3:Check if (front==rear) if it is true then set front = rear = NULL else move the front
forward in queue, update address of front in rear node and return the element.

Input:
Insert element 7 in the circular queue
426135
Output:
7426135

Post Experiment Questions:

Q1. What is the Time complexity of enQueue(), deQueue() operations?

Q2. Why it is better to use circular queue while using array implemention?

Q3. How do you count the number of elements in the circular linked list?

Q4. What is the time complexity of searching for an element in a circular linked list?

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 61
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 17

Aim: To Implement binary tree using linked list.

Description: Binary tree is a special data structure used for data storage purposes. A binary tree has
a special condition that each node can have two children at maximum. Binary Search tree exhibits a
special behaviour. A node's left child must have value less than its parent's value and node's right
child must have value greater than it's parent value. A binary tree have benefits of both an ordered
array and a linked list as search is as quick as in sorted array and insertion or deletion operation are
as fast as in linked list.

Following are important terms with respect to tree.

 Path − Path refers to sequence of nodes along the edges of a tree.

 Root − Node at the top of the tree is called root. There is only one root per tree and one path
from root node to any node.

 Parent − Any node except root node has one edge upward to a node called parent.

 Child − Node below a given node connected by its edge downward is called its child node.

 Leaf − Node which does not have any child node is called leaf node.

 Subtree − Subtree represents descendents of a node.

 Visiting − Visiting refers to checking value of a node when control is on the node.

 Traversing − Traversing means passing through nodes in a specific order.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 61
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

 Levels − Level of a node represents the generation of a node. If root node is at level
0, then its next child node is at level 1, its grandchild is at level 2 and so on.

 keys − Key represents a value of a node based on which a search operation is to be carried
out for a node.

Basic Operations

The basic operations that can be performed on binary search tree data structure, are following −

 Insert − insert an element in a tree / create a tree.

 Search − search an element in a tree.

 Preorder Traversal − traverse a tree in a preorder manner.

 Inorder Traversal − traverse a tree in an inorder manner.

 Postorder Traversal − traverse a tree in a postorder manner.

Deletion in a binary tree

if x has no children  case 0

then remove x

if x has one child  case 1

then make p[x] point to child

if x has two children (subtrees)  case 2

then swap x with its successor

perform case 0 or case 1 to delete it

TOTAL: O(h) time to delete a node

Pre Experiments Questions

Q1. What is the height of a binary tree?

Q2. What do you mean by complete binary tree?

Q3. What is the maximum no. of nodes in a binary tree of height 3?

Q4. Write the pre-, post- and in-order traversal for the given tree.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 64
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Algorithm for Insert Operation

The very first insertion creates the tree. Afterwards, whenever an element is to be inserted. First
locate its proper location. Start search from root node then if data is less than key value, search empty
location in left subtree and insert the data. Otherwise search empty location in right subtree and insert
the data.

If root is NULL

then create root node

return

If root exists then

compare the data with node.data

while until insertion position is located

If data is greater than node.data

goto right subtree

else

goto left subtree

endwhile

insert data

end If

Input:

Insert element 7 in a binary tree

426135

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 64
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Output:

4261357

Algorithm for delete Operation

Determine which node to splice out: either z or z’s successor. */

1 if left[z] = NIL or right[z] = NIL

2 then y  z

3 else y  Tree-Successor[z]

/* Set x to a non-NIL child of x, or to NIL if y has no children. */

4. if left[y]  NIL

5. then x  left[y]

6. else x  right[y]

/* y is removed from the tree by manipulating pointers of p[y] and x */

7. if x  NIL

8. then p[x]  p[y]

9. if p[y] = NIL

10. then root[T]  x

11. else if y  left[p[i]]

12. then left[p[y]]  x

13. else right[p[y]]  x

/* If z’s successor was spliced out, copy its data into z */

14. if y  z

15. then key[z]  key[y]

16. return y

Post Experiment Questions:

Q1. Disadvantage of using array representation for binary trees is .

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 64
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Q2. What must be the ideal size of array if the height of tree is ‘l’?

Q3. What is the time complexity for finding the height of the binary tree?

Q4. What are the children for node ‘w’ of a complete-binary tree in an array representation ?

Q5. What are the advantages and disadvantages of linked list representation of binary trees over
arrays?

Q6. What is the time complexity of pre-order traversal in the iterative fashion?

Q7. What is the space complexity of the post-order traversal in the recursive fashion? (d is the tree
depth and n is the number of nodes)

Q8. In a full binary tree if number of internal nodes is I, then number of leaves L are?

Q9. In a full binary tree if number of internal nodes is I, then number of nodes N are?

Q10. In a full binary tree if there are L leaves, then total number of nodes N are?

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 65
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 18

Aim: To Implement binary search tree using linked list

Description:Binary search is a fast search algorithm with run-time complexity of Ο(log n). These
search algorithms works on the principle of divide and conquer. For this algorithm to work properly
the data collection should be in sorted form. Binary search search a particular item by comparing the
middle most item of the collection. If match occurs then index of item is returned. If middle item is
greater than item then item is searched in sub-array to the right of the middle item other wise item
is search in sub-array to the left of the middle item. This process continues on sub-array as well until
the size of subarray reduces to zero.

Pre Experiment Questions:

Q1. What is the difference between linear search and binary search?

Q2. What are the properties of a binary search tree?

Algorithm for Insertion in Binary search tree:

struct node * insert(struct node* node,int key)

if (node==NULL)return newNode(key); /*if tree is empty ,return a new

node*/ if(key<node->key) /*otherwise recurse down the tree*/

node->left=insert(node->left,key);

elseif(key>node->key)

node->right=insert(node,right->key);

return node; /*return the (unchanged) node pointer */

Input:
157289
Elements to be found: 8
Output:
Elements found at position no. 5

Post Experiment Questions:

Q1.List out the applications where binary search tree is applied.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 66
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Q2. What is the worst case time complexity of search and insert operations in a BST?

Q3. What is the speciality about the inorder traversal of a binary search tree?

Q4. How will you find the minimum element in a binary search tree?

Q5. How will you find the maximum element in a binary search tree?

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 70
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 19

Aim: To implement tree traversals using linked list.

Description:Traversal is a process to visit all the nodes of a tree and may print their values too.
Because, all nodes are connected via edges (links) traversing always start from the root (head) node.
That is, why random access operation is not possible. There are three ways which we use to traverse
a tree −

 In-order Traversal
 Pre-order Traversal
 Post-order Traversal
Generally we traverse a tree to search or locate given item or key in the tree or to print all the
values it contains.

Inorder Traversal:
In this traversal method, the left left-subtree is visited first, then root and then the right sub-tree. We
should always remember that every node may represent a subtree itself. If a binary tree is traversed
inorder, the output will produce sorted key values in ascending order.

We start from A, and following in-order traversal, we move to its left subtree B.B is also traversed
in-ordered. And the process goes on until all the nodes are visited. The output of in-order traversal
of this tree will be −

D→B→E→A→F→C→G

Preorder Traversal:
In this traversal method, the root node is visited first, then left subtree and finally right sub-tree.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 70
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

We start from A, and following pre-order traversal, we first visit A itself and then move to its left
subtree B. B is also traversed pre-ordered. And the process goes on until all the nodes are visited.
The output of pre-order traversal of this tree will be −

A→B→D→E→C→F→G

Postorder Traversal:
In this traversal method, the root node is visited last, hence the name. First we traverse left subtree,
then right subtree and finally root.

We start from A, and following pre-order traversal, we first visit left subtree B.B is also traversed
post-ordered. And the process goes on until all the nodes are visited. The output of post-order
traversal of this tree will be −

D→E→B→F→G→C→A

Pre- Experiment Questions

Q1. What are the different traversing methods of Binary Tree?


Q2. What are the main applications of tree data structure?

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 70
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Q3. What is common in three different types of traversals (Inorder, Preorder and Postorder)?Q4.
What are the tasks performed during Postorder traversal?

Algorithm for In-Order traverse

Until all nodes are traversed −


Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.

Algorithm for Pre-Order traverse

Until all nodes are traversed −


Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree.
Step 3 − Recursively traverse right subtree.

Algorithm for Post-Order traverse

Until all nodes are traversed −


Step 1 − Recursively traverse left subtree.
Step 2 − Recursively traverse right subtree.
Step 3 − Visit root node.

Input:

4261357

Output:

In-Order traversal: 4 2 6 1 3 5 7
Pre-Order traversal: 4 2 1 3 6 5 7
Post-Order traversal:1 3 2 5 7 6 4

Post Experiment Questions

Q1. Which traversal algorithm traverses all the nodes of a binary tree in a sorted manner?
Q2.What is the time complexity of all traversing algorithms?

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 70
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Q3. Which of the following pairs of traversals is not sufficient to build a binary tree from the given
traversals?
(A) Preorder and Inorder
(B) Preorder and Postorder
(C) Inorder and Postorder
(D) None of the Above
Q4. What does the following function do for a given binary tree?
int fun(struct node *root)
{
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 0;
return 1 + fun(root->left) + fun(root->right);
}

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 72
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 20

Aim: To find Minimum Cost Spanning Tree of a given undirected graph using Kruskal’s
Algorithm.

Description: Kruskal's algorithm is a minimum-spanning-tree algorithm which finds an edge of the


least possible weight that connects any two trees in the forest. It is a greedy algorithm in graph theory
as it finds a minimum spanning tree for a connected weighted graph adding increasing cost
arcs at each step.
Pre- Experiments Questions
.
Q1. How many edges does a minimum spanning tree has?.
Q2. Define minimum cost spanning tree.
Q3. List all the application of minimum spanning tree.

Algorithm:

Step 2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If
cycle is not formed, include this edge. Else, discard it.
Step 3. Repeat step#2 until there are (V-1) edges in the spanning tree.

Input:

Output:

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 72
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Post- Experiment Questions

Q1. What is the time complexity of Kruskal’s algorithm and Prim’s algorithm.
Q2. What is the difference between Prim’s and Kruskal’s algorithms.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 84
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 21

Aim: To Implement Single Source Shortest Path Algorithm.

Description: Dijkstra's algorithm solves the single-source shortest path problem when all
edges have nonnegative weights. It is a greedy algorithm and similar to Prim's algorithm.Algorithm
starts at the source vertex, s, it grows a tree, T, that ultimately spans all vertices reachable from S.
Vertices are added to T in order of distance i.e., first S, then The vertex closest to S, then the next cl
osest, and so on. Following implementation assumes that graph G is represented by adjacency lists.

Pre- Experiment Questions

Q1. Dijkstra algorithm can take into account the negative edge weigthts.'Is the statement true?
Q2. What is a negative weight cycle?

Algorithm:

Step1. INITIALIZE SINGLE-SOURCE (G, s)


Step 2. S ← { } // S will ultimately contains vertices of final shortest- path weights from s
Step 3. Initialize priority queue Q i.e., Q ← V[G]
Step 4. While priority queue Q is not empty do
Step 5. u ← EXTRACT_MIN(Q) // Pull out new vertex
Step6. S ← S È {u} // Perform relaxation for each vertex v adjacent to u
Step7. for each vertex v in Adj[u] do
Step8. Relax (u, v, w)

Input:

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 84
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Output:

Post- Experiment Questions

Q1. What is the time complexity of Dijkstra's algorithm .


Q2. What is the time complexity of Flyod-Warshall algorithm

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 84
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 22

Aim: To implement a solution to Tower’s of Hannoi problem.


Description: Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and
more than one rings is as depicted −

These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one sits
over the larger one. There are other variations of the puzzle where the number of disks increase,
but the tower count remains the same.

Rules: The mission is to move all the disks to some another tower without violating the sequence of
arrangement. A few rules to be followed for Tower of Hanoi are −

 Only one disk can be moved among the towers at any given time.
 Only the "top" disk can be removed.
 No large disk can sit over a small disk.

Following is an animated representation of solving a Tower of Hanoi puzzle with three disks.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 84
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This presentation
shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps.

Pre Experiment Questions:

Q1. Which data structure can be used suitably to solve the Tower of Hanoi problem?
a) Tree
b) Heap
c) Priority queue
d) Stack

Algorithm:

o write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem with lesser
amount of disks, say → 1 or 2. We mark three towers with name, source, destination and aux (only
to help moving the disks). If we have only one disk, then it can easily be moved from source to
destination peg.
If we have 2 disks −
 First, we move the smaller (top) disk to aux peg.
 Then, we move the larger (bottom) disk to destination peg.
 And finally, we move the smaller disk from aux to destination peg.

So now, we are in a position to design an algorithm for Tower of Hanoi with more than two disks.
We divide the stack of disks in two parts. The largest disk (nth disk) is in one part and all other (n-
1) disks are in the second part.
Our ultimate aim is to move disk n from source to destination and then put all other (n1) disks onto
it. We can imagine to apply the same in a recursive way for all given set of disks.
The steps to follow are −

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 84
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Step 1 − Move n-1 disks from source to aux


Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest

A recursive algorithm for Tower of Hanoi can be driven as follows

START

Procedure Hanoi(disk, source, dest, aux)

IF disk == 1, THEN

move disk from source to dest

ELSE

Hanoi(disk - 1, source, aux, dest) // Step 1

move disk from source to dest // Step 2

Hanoi(disk - 1, aux, dest, source) // Step 3

END IF

END Procedure

STOP

Post Experiment Questions:


Q1. What is the number of moves required in the Tower of Hanoi problem for k disks?

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 84
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 23

Aim: Write a Program to convert from Infix to Prefix and Postfix representation of an
expression.

Description: The way to write arithmetic expression is known as a notation. An arithmetic


expression can be written in three different but equivalent notations, i.e., without changing the
essence or output of an expression. These notations are −
 Infix Notation
 Prefix (Polish) Notation
 Postfix (Reverse-Polish) Notation
These notations are named as how they use operator in expression. We shall learn the same here in
this chapter.
Infix Notation
We write expression in infix notation, e.g. a - b + c, where operators are used in-between operands.
It is easy for us humans to read, write, and speak in infix notation but the same does not go well with
computing devices. An algorithm to process infix notation could be difficult and costly in terms of
time and space consumption.
Prefix Notation
In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For
example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known as Polish
Notation.
Postfix Notation
This notation style is known as Reversed Polish Notation. In this notation style, the operator is
postfixed to the operands i.e., the operator is written after the operands. For example, ab+. This is
equivalent to its infix notation a + b.
The following table briefly tries to show the difference in all three notations −
Sr.No. Infix Notation Prefix Notation Postfix Notation
1 a+b +ab ab+
2 (a + b) ∗ c ∗+abc ab+c∗

3 a ∗ (b + c) ∗a+bc abc+∗

4 a/b+c/d +/ab/cd ab/cd/+


5 (a + b) ∗ (c + d) ∗ + a b + c d ab+cd+∗

6 ((a + b) ∗ c) - d -∗+abcd ab+c∗d-

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 84
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Pre Experiment Questions:


Q1. Fill the table with operator precedence and associativity (highest to lowest) −
Sr.No. Operator Precedence Associativity
1 Exponentiation ^
2 Multiplication ( ∗ ) & Division ( / )

3 Addition ( + ) & Subtraction ( − )

Q2. Which data structure is used to convert infix notations to pre and postfix notations?
Algorithm to convert an infix notation to Postfix notation:
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
…..3.1 If the precedence of the scanned operator is greater than the precedence of the
operator in the stack(or the stack is empty), push it.
…..3.2 Else, Pop the operator from the stack until the precedence of the scanned operator is
less-equal to the precedence of the operator residing on the top of the stack. Push the scanned
operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it is not empty.

Algorithm to convert an infix notation to Postfix notation:


1. Reverse the infix expression i.e A+B*C will become C*B+A. Note while reversing each
‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘.
2. Obtain the postfix expression of the modified expression i.e CB*A+.
3. Reverse the postfix expression. Hence in our example prefix is +A*BC.

Post Experiment Questions:


Q1. Why postfix representation of the expression?
Q2. Convert the following infix notation to post and prefix notations using stack.
a+b*(c^d-e)^(f+g*h)-i
Q3. What is the timecomplexity of the algorithm to convert infix notation to pre and postfix
notation?

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 84
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

EXPERIMENT - 24

Aim: Write a Program to evaluate Prefix and Postfix representation of an expression.

Description: Prefix and Postfix expressions can be evaluated faster than an infix expression. This is
because we don’t need to process any brackets or follow operator precedence rule. In postfix and
prefix expressions which ever operator comes before will be evaluated first, irrespective of its
priority. Also, there are no brackets in these expressions. As long as we can guarantee that a valid
prefix or postfix expression is used, it can be evaluated with correctness.
Postfix Evaluation Algorithm:

1) Create a stack to store operands (or values).


2) Scan the given expression and do following for every scanned element.
…..a) If the element is a number, push it into the stack
…..b) If the element is a operator, pop operands for the operator from stack. Evaluate the
operator and push the result back to the stack
3) When the expression is ended, the number in the stack is the final answer

Prefix Evaluation Algorithm:

1. Accept a prefix string from the user.

2. say (-*+ABCD), let A=4, B=3, C=2, D=5

3. i.e. (-*+4325) is the input prefix string.

4. Start scanning the string from the right one character at a time.

5. If it is an operand, push it in stack.

6. If it is an operator, pop opnd1, opnd2 and perform the operation, specified by the operator.
Push the result in the stack.

7. Repeat these steps until arr of input prefix strings ends.

For evaluation of prefix notation:

Input : -+8/632

Output : 8

For evaluation of postfix notation

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 84
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

Input: 231*+9-

Output : -4

Post Experiment Questions:

Q1. Evaluate the postfix notation 2 3 1 * + 9 – using the implemented algorithm. Show all the steps.

Q2. Evaluate the postfix notation - + 8 / 6 3 2 using the implemented algorithm. Show all the steps.

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 84
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

References

1. Aaron M. Tenenbaum, Yedidyah Langsam and Moshe J. Augenstein, “Data Structures Using C
and C++”,PHI Learning Private Limited, Delhi India

2. Horowitz and Sahani, “Fundamentals of Data Structures”, Galgotia Publications Pvt Ltd DelhI
India.

3. Lipschutz, “Data Structures” Schaum’s Outline Series, Tata McGraw-hill Education (India) Pvt.
Ltd.

4. Thareja, “Data Structure Using C” Oxford Higher Education.

5. AK Sharma, “Data Structure Using C”, Pearson Education India.

6. Rajesh K. Shukla, “Data Structure Using C and C++” Wiley Dreamtech Publication.

7. Michael T. Goodrich, Roberto Tamassia, David M. Mount “Data Structures and Algorithms in
C++”,Wiley India.

8. P. S. Deshpandey, “C and Data structure”, Wiley Dreamtech Publication.

9. R. Kruse etal, “Data Structures and Program Design in C”, Pearson Education.

10. Berztiss, AT: Data structures, Theory and Practice, Academic Press.

11. Jean Paul Trembley and Paul G. Sorenson, “An Introduction to Data Structures with
applications”,McGraw Hill.

12. Adam Drozdek “Data Structures and Algorithm in Java”, Cengage Learning

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 84
JSS Academy of Technical Education – NOIDA
Department of Computer Science and Engineering

APPENDIX

AKTU SYLLABUS

BCS351: DATA STRUCTURE LAB

List of Experiments (Indicative & not limited to)


1. Implementing Sorting Techniques: Bubble Sort, Insertion Sort, Selection Sort, Shell, Sort, Radix
Sort, Quick sort

2. Implementing Searching and Hashing Techniques: Linear search, Binary search, Methods for
Hashing: Modulo Division, Digit Extraction, Fold shift, Fold Boundary, Linear Probe for Collision
Resolution. Direct and Subtraction hashing

3. Implementing Stacks: Array implementation, Linked List implementation, Evaluation of postfix


expression and balancing of parenthesis , Conversion of infix notation to postfix notation

4. Implementing Queue: Linked List implementation of ordinary queue, Array implementation of


circular queue, Linked List implementation of priority queue, Double ended queue

5. Implementing Linked List: Singly Linked Lists, Circular Linked List, Doubly Linked Lists :
Insert, Display, Delete, Search, Count, Reverse(SLL), Polynomial , Addition , Comparative study of
arrays and linked list

6. Implementing Trees: Binary search tree : Create, Recursive traversal: preorder, post order, in
order, Search Largest , Node, Smallest Node, Count number of nodes, Heap: Min Heap, Max Heap:
reheap Up, reheap Down, Delete , Expression Tree, Heapsort

7. Implementing Graphs: Represent a graph using the Adjacency Matrix, BFS, Find the minimum
spanning tree (using any method Kruskal’s Algorithm or Prim’s Algorithm) Self Learning

Topics : Shortest Path Algorithm

Data Structure Lab (BCS 351) Manual (CS, III Sem) Page | 84

You might also like