Marathwada Mitra Mandal’s
College of Engineering, Pune
Karve Nagar,Pune-411 052
Department of Artificial Data Structure laboratory
Intelligence and Data Science
Engineering
Data Structure Laboratory
( 217522)
Prepared by:
Ms. Sonali P
Potadar
Lab Man
S.E –AI & DS
Semester III Academic Year 2024-25
PROGRAMS OUTCOMES (POs)
Engineering Graduates will be able to:
1. Engineering Knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals and an engineering specialization to the solution of
complex engineering problems.
Data
2. Problem Analysis: Identity, formulate, review research literature, Structure
and analyzelaboratory
complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
3. 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.
4. 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.
5. 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.
6. 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.
7. 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.
8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
Data Structure laboratory
9. Individual and team work: Function effectively as an individual, and as a
member or leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.
11. 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.
12. 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.
Course Objective & Course Outcomes
Course Objectives:
To understand basic techniques and strategies of algorithm analysis, the memory
requirement for various data structures like array, linked list, stack, queue etc using
concepts of python and C++ programming language.
Course Outcomes:
After successfully completing the course students will be able to
1. Use algorithms on various linear data structure using sequential organization to solve real
life problems. Data Structure laboratory
2. Analyze problems to apply suitable searching and sorting algorithm to various applications
3. Analyze problems to use variants of linked list and solve various real-life problems.
4. Designing and implement data structures and algorithms for solving different kinds of
problems.
CO-PO Mapping Matrix
PO
SUBJECT PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11
12
CO1 1 1 2 1
Data
CO2 2 2 2 1
Structure CO3 - 2 1 1
Laboratory CO4 1 2 2 1
Data Structures Laboratory (217522)
Teaching Scheme: Lectures: 3Hrs/week Practical: 4 hrs./week
Examination Scheme: Term work :25 Marks Practical :50Marks
Theory: 100 Marks
List Of assignments
Sr. No Title of Assignment
1. In second year computer engineering class, group A student’s play cricket,
group B students play badminton and group C students play football. Write
a Python program using functions to compute following: -
a) List of students who play both cricket and badminton
b) List of students who play either cricket or badminton but not Data
both Structure laboratory
c) Number of students who play neither cricket nor badminton
d) Number of students who play cricket and football but not badminton.
2. Write a Python program to store marks scored in subject “Fundamental of
Data Structure” by N students in the class. Write functions to compute
following:
a) The average score of class
b) Highest score and lowest score of class
c) Count of students who were absent for the test
d) Display mark with highest frequency
3. Write a python program to compute following computation on matrix:
a) Addition of two matrices
b) Subtraction of two matrices
c) Multiplication of two matrices
d) Transpose of a matrix
4 Write a python program to maintain club members, sort on roll numbers in
ascending order. Write function “Ternary Search” to search whether
particular student is member of club or not. Ternary search is modified
binary search that divides array into 3 halves instead of two.
5. Write a python program to store first year percentage of students in array.
Write function for sorting array of floating point numbers in ascending order
using
a) Selection Sort
b) Bubble sort and display top five scores.
6. Write a python program to store 12th class percentage of students in
array. Write function for sorting array of floating point numbers in ascending
order using bucket sort and display top five scores.
7. Department of Computer Engineering has student's club named 'Pinnacle
Club'. Students of second, third and final year of department can be
granted membership on request. Similarly one may cancel the membership
of club. First node is reserved for president of club and last node is
reserved for secretary of club. Write C++ program to maintain club
member‘s information using singly linked list. Store student PRN and
Name. Write functions to:
a) Add and delete the members as well as president or even secretary.
b) Compute total number of members of club
c) Display members
d) Two linked lists exists for two divisions. Concatenate two lists.
8. Write C++ program for storing binary number using doubly linked lists.
Write functions-
a) To compute 1‘s and 2‘s complement
b) Add two binary numbers
9. A palindrome is a string of character that‘s the same forward and laboratory
Data Structure
backward. Typically, punctuation, capitalization, and spaces are ignored.
For example, “Poor Dan is in a droop” is a palindrome, as can be seen by
examining the characters “poor danisina droop” and observing that they are
the same forward and backward. One way to check for a palindrome is to
reverse the characters in the string and then compare with them the
original-in a palindrome, the sequence will be identical. Write C++ program
with functions-
a) To print original string followed by reversed string using stack
b) To check whether given string is palindrome or not
10. In any language program mostly syntax error occurs due to unbalancing
delimiter such as (),{},[]. Write C++ program using stack to check whether
given expression is well parenthesized or not.
11. Queues are frequently used in computer programming, and a typical
example is the creation of a job queue by an operating system. If the
operating system does not use priorities, then the jobs are processed in the
order they enter the system. Write C++ program for simulating job queue.
Write functions to add job and delete job from queue.
12. A double-ended queue (deque) is a linear list in which additions and
deletions may be made at either end. Obtain a data representation
mapping a deque into a one-dimensional array. Write C++ program to
simulate deque with functions to add and delete elements from either end
of the deque.
13. Pizza parlor accepting maximum M orders. Orders are served in first come
first served basis. Order once placed cannot be cancelled. Write C++
program to simulate the system using circular queue using array.
Experiment No. 1
Title: - Python program to perform different set operations.
Aim: - In second year computer engineering class, group A student’s play cricket, group B
students play badminton and group C students play football. Write a Python program using
functions to compute following: -
a) List of students who play both cricket and badminton
b) List of students who play either cricket or badminton but not both
c) Number of students who play neither cricket nor badminton
d) Number of students who play cricket and football but not badminton.
Data Structure laboratory
Software used: Python
O.S: used 64 bit open source Linux
Theory: -
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be
immutable (cannot be changed).However, a set itself is mutable. We can add or remove items
Mapped to Course Objective:
from it. Sets can also be used to perform mathematical set operations like union, intersection,
To understand different set operations in Python.
symmetric difference, etc.
To learn and implement set operations without using SET() function.
Set operations can be implemented in Python using List -Data type.
Mapped to Course Outcome:
List
After successfully performing this experiment, the student will be able to und
Lists are used to store multiple items in aset
different single variable.
operations
Lists are one of 4 built-in data types in Python used to store collections of data
Lists are created using square brackets:
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order
will not change. Data Structure laboratory
If you add new items to a list, the new items will be placed at the end of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has
been created.
Allow Duplicates
lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
List Items - Data Types
List items can be of any data type:
Example
string, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
A list can contain different data types:
Example
Data Structure laboratory
A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current
list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Algorithm:-
1. Start
2. Create different empty list SEComp=[],Cricket=[],football=[] and Badminton[].
3. Read the values of students play cricket, badminton and football.
Data Structure laboratory
4. Declare function removeduplicate() to remove duplicate entries, Intersection()-to find the
intersection of two lists, union()-to find the union of two lists,diff()- to find the difference of
two lists, sym_diff()-to find the symmetric difference of two lists.
5. Declare CB(),eCeB(), nCnB() and CBnF() functions for finding no. of students who play
cricket and badminton, either cricket or badminton, neither cricket nor badminton and
cricket ,badminton nor football respectively.
6. Display respective results.
7. Stop.
Conclusion:-
Thus all set operations have been studied and implemented without using Python List data
type without using built in set() function
Frequently Asked Questions:
1. What operations can be done on a set in Python?
2. When would you use a set Python?
3. Can sets have different data types?
4. Is set mutable or immutable?
5. Are sets faster than lists Python?
Input-output
Enter all students (space-separated): Sonali Mayuri Sinu Tejal Madhavi Ashlesha
Snehal Pooja Simran Manisha
Enter students who play cricket (space-separated): Sonali Sinu Mayur
Enter students who play badminton (space-separated): Tejal Mayuri Ashlesha Snehal
Enter students who play football (space-separated): Madhavi Pooja Simram Manisha
Sinu
Students who play both cricket and badminton: set()
Students who play either cricket or badminton but not both: {'Mayuri', 'Ashlesha',
'Mayur', 'Sinu', 'Snehal', 'Sonali', 'Tejal'}
Number of students who play neither cricket nor badminton: 4
Number of students who play cricket and football but not badminton: 1
Enter all students (space-separated): Sonali Mayuri Sinu Tejal Madhavi Ashlesha
Snehal Pooja Simran Manisha
Enter students who play cricket (space-separated): Mayuri Sonali Simran Manisha
Enter students who play badminton (space-separated): Sinu Sonali Ashlesha Snehal
Pooja Data Structure laboratory
Enter students who play football (space-separated): Sonali Manisha Madhavi Simran
Tejal Mayuri
Students who play both cricket and badminton: {'Sonali'}
Students who play either cricket or badminton but not both: {'Mayuri', 'Ashlesha',
'Sinu', 'Pooja', 'Manisha', 'Snehal', 'Simran'}
Number of students who play neither cricket nor badminton: 2
Number of students who play cricket and football but not badminton: 3
Experiment No. 2
Title: - Python program to write different functions to perform operations on student records.
Aim: - Write a Python program to store marks scored in subject “Fundamental of Data
Structure” by N students in the class. Write functions to compute following:
a) The average score of class
b) Highest score and lowest score of class
c) Count of students who were absent for the test
d) Display mark with highest frequency
Data Structure laboratory
Software used: - Python
O.S: used 64-bit open source
Linux
Theory: -
Python Functions
In Python, a function is a group of related statements that performs a specific task.
Functions help break our programMapped
into smaller and modular
to Course chunks. As our program grows
Objective:
larger and larger, functions make it more organized and manageable. Furthermore,
To learn and understand types of functions it avoids
in Python.
repetition and makes the code reusable.
Syntax of Function Mapped to Course Outcome:
After successfully performing this experiment, the student will be ab
defined functions in python
1. Keyword def that marks the start of the function header.
2. A function name to uniquely identify the function. Function naming follows the same rules
of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must
have the same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
Example of a function
Data Structure laboratory
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good
Once we have defined a function, we can call it from another function, program, or even the
Python prompt. To call a function we simply type the function name with appropriate parameters.
Types of Functions
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.
Built-in functions
Python has several functions that are readily available for use. These functions are called built-in
functions. On this reference page, you will find all the built-in functions in Python.
Examples
Data Structure laboratory
● print( ) : prints the specified message to the screen or another standard output device
● type( ): returns the type of the specified object.
● input( ): allows taking the input from the user
● abs( ): returns the absolute value of the specified number.
● pow( ): returns the calculated value of x to the power of y i.e, xy
● dir( ): returns all the properties and methods of the specified object, without the values.
● sorted( ) : returns a sorted list of the specified iterable object.
● max( ) : returns the item with the maximum value or the item with the maximum value in an
iterable.
● round( ): returns a floating-point number that is a rounded version of the specified number,
with the specified number of decimals.
● divmod( ): returns a tuple containing the quotient and the remainder when the first
argument i.e, the dividend is divided by the second argument i.e, the divisor.
User- defined function
Advantages of User-defined Functions in Python
1. This Python Function help divide a program into modules. This makes the code easier
to manage, debug, and scale.
2. It implements code reuse. Every time you need to execute a sequence of statements,
all you need to do is to call the function.
3. This Python Function allow us to change functionality easily, and different
programmers can work on different functions.
Algorithm:-
1. Start
2. Read the number of students and their marks assigned to markesinFDS[].
3. Write functions avg(marksinFDS),Max(marksinFDS),Min(marksinFDS),absentcount(
marksinFDS),maxfreq( marksinFDS). Data Structure laboratory
4. While flag=1
If Ch=1 call avg(marksinFDS) display result else ;
If Ch=2 call Max(marksinFDS), Min(marksinFDS) display result else
If Ch=3 call absentcount(marksinFDS) display result else
If Ch= 4 call maxfreq( marksinFDS) display result else
If Ch=5 exit
5. Stop
Conclusion:- The types of functions in python have been studied and the operations on
students records have implemented using user defined functions.
Frequently Asked Questions:
1. What are functions in Python explain with example?
2. What are the 4 types of functions in Python?
3. What is the need of function in Python?
4. Which key is used for function in Python?
Input-output
Enter marks for each student (use 'A' for absent, space-separated): 57 A 78 A A 77
56 90 34 A 67 78
Average score of the class: 67.125
Highest score of the class: 90
Lowest score of the class: 34
Number of students absent for the test: 4
Mark with highest frequency: 78
Frequency of that mark: 2
Enter marks for each student (use 'A' for absent, space-separated): 67 80 A A 77
66 45 23 29 50 A 77
Average score of the class: 57.111111111111114
Highest score of the class: 80
Lowest score of the class: 23 Data Structure laboratory
Number of students absent for the test: 3
Mark with highest frequency: 77
Frequency of that mark: 2
Experiment No. 3
Title: - Python program to perform operations on Matrix.
Aim: - Write a python program to compute following computation on matrix:
a) Addition of two matrices
b) Subtraction of two matrices
c) Multiplication of two matrices
d) Transpose of a matrix
Data Structure laboratory
Software used:- Python
O.S: used 64-bit open source Linux
Theory: -
Matrix is a special case of two dimensional array where each data element is of strictly
Mapped to Course Objective:
same size. So every matrix is also a two dimensional array but not vice versa. Matrices
To learn and understand basics of 1D and 2D array.
are very important data structures for many mathematical and scientific calculations.
Develop an ability to write programs in Python for problem solving.
Mapped to Course Outcome:
After successfully performing this experiment, the student will be able t
python.
In Python, we can take a user input matrix in different ways. The method for user input matrix in
Python
are shown below:
Data Structure laboratory
A basic code for matrix input from user
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
# Initialize matrix
matrix = []
print("Enter the entries rowwise:")
# For user input
for i in range(R): # A for loop for row entries
a =[]
for j in range(C): # A for loop for column entr
a.append(int(input()))
matrix.append(a)
# For printing the matrix
for i in range(R):
for j in range(C):
print(matrix[i][j], end = " ")
print()
Algorithm: -
1. Start
2. Read number of rows (r1, r2) and Columns(c1,c2) of matrix M1,M2.
3. Read elements of Matrix
4. If ch=1 call addition_matrix(M1,M2,M3,r1,c1) display result.
If ch=2 call substraction_matrix(M1,M2,M3,r1,c1) display result.
If ch=3 call multiplication_matrix(M1,M2,M3,r1,c1) display result.
If ch=4 call transpose_matrix(M1,M2,M3,r1,c1) display result.
If ch=5 exit
5. Stop
Data Structure laboratory
Conclusion: -
Python matrix is a specialized two-dimensional structured array. The Python matrix
elements from various data types such as string, character, integer, expression, symbol etc.
Python matrix can be defined with the nested list method .We can perform various matrix
operations on the Python matrix.
Frequently Asked Questions:
1. What are the operations we can perform in a matrix?
2. How do you know if two matrices can be multiplied in Python?
3. Is a matrix the same as an array in Python?
4. What is the difference between array and matrix in Python?
5. Can you change order of matrix multiplication?
6. Can a list be in a matrix?
Input-output
Enter the number of rows for Matrix 1: 3
Enter the number of columns for Matrix 1: 3
Enter the elements of Matrix 1:
1 2 3
1 2 3
1 2 3
Enter the number of rows for Matrix 2: 3
Enter the number of columns for Matrix 2: 3
Enter the elements of Matrix 2:
1 1 1
2 2 2
3 3 3
Addition of two matrices:
[[2 3 4]
[3 4 5]
[4 5 6]]
Subtraction of two matrices: Data Structure laboratory
[[ 0 1 2]
[-1 0 1]
[-2 -1 0]]
Multiplication of two matrices:
[[14 14 14]
[14 14 14]
[14 14 14]]
Transpose of Matrix 1:
[[1 1 1]
[2 2 2]
[3 3 3]]
Experiment No. 4
Title: - Python program to implement Ternary
search.
Aim: - Write a python program to maintain club members, sort on roll numbers in ascending
order. Write function “Ternary Search” to search whether particular student is member of club
or not. Ternary search is modified binary search that divides array into 3 halves instead of two
Data Structure laboratory
Software used:- Python
O.S: used 64-bit open-source
Linux Mapped to Course Objective:
Theory: - To learn and understand data searching method.
To find the complexity of the Ternary Search
Ternary search is a searching algorithm that searches an element in a sorted array.
Mapped to Course Outcome:
Like linear search and binary search, ternary search is a searching technique that is used to
After successfully performing this experiment, the student will be able t
determine the position of a specific value in an array. In binary search, the sorted array is
the computational efficiency of the Ternary search method
divided into two parts while in ternary search, it is divided into 3 parts and then you determine
in which part the element exists.
Ternary search, like binary search, is a divide-and-conquer algorithm. It is mandatory for the
array (in which you will search for an element) to be sorted before you begin the search. In this
search, after each iteration it neglects ⅓⅓ part of the array and repeats the same operations
on the remaining ⅔⅔.
Example
Data Structure laboratory
Algorithm: -
1. Let X be the value we wish to search for.
2. We use 2 variables start and end to mark the beginning index and ending index of the
given array.
3. Repeat the following steps while start<=end.
1. We calculate 2 mids, mid1 and mid2
mid1 = (end-start)/3 + start
mid2 = 2*(end-start)/3 + start
The array is now divided into 3 parts,
● [start,mid1]
● [mid1,mid2]
● [mid2,end]
2. If X is equal to arr[mid1] or arr[mid2], we return the index of X and terminate
the program.
3. If X lies in interval [start,mid1), set end = mid1 – 1.
4. If X lies in the interval (mid1,mid2), set start = mid1 + 1 and end = mid2 – 1.
5. Else X lies in the interval (mid2,end], set start = mid2 + 1.
4. If X is not present in the array, return -1.
Ternary Search without Recursion
Data Structure laboratory
Pseudo Code:
Assuming the array is sorted in increasing(ascending order) order
arr: Array we want to search
x: value we want to search in arr
Integer Ternary_Search( arr , x )
start := 0
end := arr.LENGTH - 1
WHILE start <= end DO
mid1 := (end - start)/3 + start
mid2 := 2*(end - start)/3 + start
IF x == arr[mid1] THEN
return mid1
ELSE IF x == arr[mid2] THEN
return mid2
ELSE IF x < arr[mid1] THEN
end := mid1 - 1
ELSE IF x < arr[mid2] THEN
start := mid1 + 1
end := mid2 - 1
Ternary Search with recursion
arr: Array we want to search
x: value we want to search in arr
N: size of array
Integer Ternary_Search( arr , x , start , end )
WHILE start <= end DO Data Structure laboratory
mid1 := (end - start)/3 + start
mid2 := 2*(end - start)/3 + start
IF x == arr[mid1] THEN
return mid1
ELSE IF x == arr[mid2] THEN
return mid2
ELSE IF x < arr[mid1] THEN
return Ternary_Search( arr , x , start , mid1 - 1 )
Time Complexity: ELSE IF x < arr[mid2] THEN
return Ternary_Search( arr , x , mid1 + 1 , mid2 - 1 )
ELSE
● It is clear that on each iteration, array is reduced to 1/3 of it’s size.
return Ternary_Search( arr , x , mid2 + 1 , end )
● In worst case, the value X is not present inEND the ELSEIF
array.
● The program will terminate when start becomes less than end, that is the size of array
END WHILE
becomes 0. return -1
Now, let N be the size of the array END FUNCTION
● After the first iteration
Size of array = N/3
● After the second iteration
Size of array = N/32
…..
…..
● After the Kth iteration
Size of array = N/3k
The problem will terminate when N/3k = 1
N/3k = 1
N = 3k
k = log3(N)
The worse case requires K iterations.
Hence, the time complexity is O(log3(N)).
Time Complexity using recurrence relation
The array is reduced to 1/3 of it’s size on every iteration. Thus, the recurrence relation of
Ternary search is
T(N) = T(N/3) + C
where C is the constant
T(N) = T(N/3) + C …1
T(N/3) = T(N/32) + C …2
T(N/32) = T(N/33) + C …3
.....
.....
T(9) = T(3) + C …k-1
T(3) = T(1) + C …k
On adding equation 1 to k, we get Data Structure laboratory
T(N) = T(1) + k*C
We can observe that,
N/3k = 1
k = log3(N)
T(N) = T(1) + log3(N)*C
Since T(1) and C are constants, we can ignore them
T(N) = log3(N)
Hence, the time complexity is O(log3(N))
Conclusion:-
The time complexity of the binary search is more than the ternary search but it does
not mean that ternary search is better. In reality, the number of comparisons in
ternary search much more which makes it slower than binary search.
Frequently Asked Questions:
1. In which situation we can use ternary search?
2. How many comparisons are in ternary search?
3. What is the difference between binary search and ternary search?
Input-Output:
Enter the number of club members: 10
Enter roll number of the member: 6
Enter roll number of the member: 7
Enter roll number of the member: 12
Enter roll number of the member: 4
Enter roll number of the member: 5
Enter roll number of the member: 14
Enter roll number of the member: 9
Enter roll number of the member: 11
Enter roll number of the member: 13
Enter roll number of the member: 4
Sorted list of club members: [4, 4, 5, 6, 7, 9, 11, 12, 13, 14]
Enter roll number to check for membership: 9
Student with roll number 9 is a member of the club.
Data Structure laboratory
Experiment No. 5
Title: - Python program to sort data using selection sort and Bubble sort.
Aim: - Write a python program to store first year percentage of students in an array. Write
function for sorting array of floating-point numbers in ascending order using
a) Selection Sort
b) Bubble sort and display top five scores.
Data Structure laboratory
Software used:- Python
O.S: used 64-bit open
source Linux
Theory: -
Mapped to Course Objective:
Selection sort is a sorting algorithm that selects the smallest element from an unsorted
To understand
list in each iteration and places that element the conceptofofthe
at the beginning selection sortlist.
unsorted and bubble sort
Working of Selection Sort
Mapped to Course Outcome:
1. Set the first element as minimumAfter successfully performing this experiment, the student will be able
complexity of the algorithms
2. Compare minimum with the second element. If the second element is smaller than
minimum, assign the second element as minimum.Compare minimum with the third
element. Again, if the third element is smaller, then assign minimum to the third
element otherwise do nothing. The process goes on until the last element.
3. After each iteration, minimum is placed in the front of the unsorted list.
4. For each iteration, indexing starts from the first unsorted element. Step
Data 1 to 3 are
Structure laboratory
repeated until all the elements are placed at their correct positions.
Selection Sort Complexity = O(n2)
Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them
until they are in the intended order.
Working of Bubble Sort
Suppose we are trying to sort the elements in ascending order.
1. First Iteration (Compare and Swap)
1. Starting from the first index, compare the first and the second elements.
2. If the first element is greater than the second element, they are swapped.
3. Now, compare the second and the third elements. Swap them if they are not in order.
4. The above process goes on until the last element.
Data Structure laboratory
Complexity: O(n2)
Algorithm:-
1. selectionSort(array, size)
2. repeat (size - 1) times
3. set the first unsorted element as the minimum
4. for each of the unsorted elements
5. if element < currentMinimum
6. set element as new minimum
7. swap minimum with first unsorted position
8. end selectionSort
9. bubbleSort(array)
10. for i <- 1 to indexOfLastUnsortedElement-1
11. if leftElement > rightElement
12. swap leftElement and rightElement
13. end bubbleSort
Conclusion:- Thus selection and bubble sort algorithms have been studied and
implemented to sort the data in ascending order. Data Structure laboratory
Frequently Asked Questions:
1. Does selection sort take a long time?
2. How many swaps are there in selection sort?
3. Which is better insertion or selection sort?
4. How many passes are required in bubble sort?
5. How many times does bubble sort need to run?
6. What is the best case of bubble sort?
Input-Output:
Selection Sort - Sorted Percentages:
[67.8, 78.9, 79.5, 82.4, 85.6, 88.3, 90.4, 91.3, 92.1, 94.2]
Top Five Scores:
94.2
92.1
91.3
90.4
88.3
Bubble Sort - Sorted Percentages:
[67.8, 78.9, 79.5, 82.4, 85.6, 88.3, 90.4, 91.3, 92.1, 94.2]
Top Five Scores:
94.2
92.1
91.3
90.4
88.3
Experiment No. 6
Title: - Python program to implement quick sort.
Aim: - Write a python program to store first year percentage of students in array.
Write function for sorting array of floating point numbers in ascending
Dataorder usinglaboratory
Structure
quick sort and display top five scores.
Software used:- Python
O.S: used 64-bit open
source Linux Mapped to Course Objective:
Theory: -
Tothe
Quicksort is a sorting algorithm based on understand basicconquer
divide and concept ofapproach
bucket sort.where
1. An array is divided into subarrays by selecting a pivot element (element selected
from the array). Mapped to Course Outcome:
. After successfully performing this experiment, the student will be able to u
While dividing the array, the pivot element should be positioned in such a way that
complexity of the algorithms
elements less than pivot are kept on the left side and elements greater than pivot are
on the right side of the pivot.
2. The left and right subarrays are also divided using the same approach. This process
continues until each subarray contains a single element.
3. At this point, elements are already sorted. Finally, elements are combined to form a
sorted array.
Working of Quicksort Algorithm
Data Structure laboratory
Data Structure laboratory
Data Structure laboratory
Algorithm:-
quickSort(array, leftmostIndex, rightmostIndex)
if (leftmostIndex < rightmostIndex)
pivotIndex <- partition(array,leftmostIndex, rightmostIndex)
quickSort(array, leftmostIndex, pivotIndex - 1)
quickSort(array, pivotIndex, rightmostIndex)
partition(array, leftmostIndex, rightmostIndex)
set rightmostIndex as pivotIndex
storeIndex <- leftmostIndex - 1
for i <- leftmostIndex + 1 to rightmostIndex
if element[i] < pivotElement
swap element[i] and element[storeIndex]
storeIndex++
swap pivotElement and element[storeIndex+1]
return storeIndex + 1
Conclusion:-
Thus Quick sort algorithms have been studied and implemented to sort the data in
ascending order.
Frequently Asked Questions:
1. What is the best running time of a quick sort algorithm?
2. How many comparisons are required in quick sort?
3. Why quicksort is called Quick?
4. Where quick sort is used in real life?
Input-Output:
Quick Sort - Sorted Percentages: Data Structure laboratory
[67.8, 78.9, 79.5, 82.4, 85.6, 88.3, 90.4, 91.3, 92.1, 94.2]
Top Five Scores:
94.2
92.1
91.3
90.4
88.3
Experiment No. 7
Title: - C++ program to implement singly linked list .
Aim: - Department of Computer Engineering has student's club named 'Pinnacle
Club'. Students of second, third and final year of department can be granted
membership on request. Similarly one may cancel the membership of club. First node
is reserved for president of club and last node is reserved for secretary of club. Write
C++ program to maintain club member‘s information using singly linked list. Store
student PRN and Name. Write functions to:
a) Add and delete the members as well as president or even secretary.
b) Compute total number of members of club
c) Display members Data Structure laboratory
d) Two linked lists exists for two divisions. Concatenate two lists.
Software used:- C++
O.S: used 64-bit open
source Linux
Theory: -
Mapped
A singly linked list is a type of linked list that to Course Objective:
is unidirectional, i.e., it can be traversed in only
one direction from the head to the last node
To(tail).
learn Each element inbasic
and understand a linked list is called
concepts a list data structur
of linked
node. A single node contains data and a pointer to the next node, which helps to maintain the
structure of the list.
Mapped to Course Outcome:
After successfully performing this experiment, the stud
understand the implementation of linked list data structure and
problem.
Representation of Linked List
Let's see how each node of the linked list is represented. Each node consists:
● A data item
● An address of another node
struct node
{
int data; Data Structure laboratory
struct node *next;
};
Basic linked list operations
Traversal - access each element of the linked list
Insertion - adds a new element to the linked list
Deletion - removes the existing elements
Search - find a node in the linked list
Sort - sort the nodes of the linked list
Traverse a Linked List
Displaying the contents of a linked list is very simple. We keep moving the temp node to
the next one and display its contents. When temp is NULL, we know that we have reached
the end of the linked list so we get out of the while loop.
struct node *temp = head;
printf("\n\nList elements are - \n");
while(temp != NULL) {
printf("%d --->",temp->data);
temp = temp->next;
}
Insert Elements to a Linked List
You can add elements to either the beginning, middle or end of the linked list.
1. Insert at the beginning
● Allocate memory for new node
● Store data
● Change next of new node to point to head
● Change head to point to recently created node
2. Insert at the End Data Structure laboratory
● Allocate memory for new node
● Store data
● Traverse to last node
● Change next of last node to recently created node
struct node *newNode;
newNode = malloc(sizeof(struc
newNode->data = 4;
newNode->next = head;
head = newNode;
3. Insert at the Middle
● Allocate memory and store data for new node
● Traverse to node just before the required position of new node struct node *newNod
newNode = malloc(si
newNode->data = 4;
newNode->next = NU
struct node *temp = h
while(temp->next !=
● Change next pointers to include new node in between
4 Delete from a Linked List
struct node *newNode;
newNode = malloc(sizeof(struct
Datanode));
Structure laboratory
You can delete either from the beginning, end newNode->data
or from a particular
= 4; position.
1. Delete from beginning struct node *temp = head;
● Point head to the second node for(int i=2; i < position; i++) {
head = head->next; if(temp->next != NULL) {
temp = temp->next;
2. Delete from end }
}
● Traverse to second last element newNode->next = temp->next;
● Change its next pointer to null temp->next = newNode;
3. Delete from middle
● Traverse to element before the element to be deleted
● Change next pointers to exclude the node from the chain
Search an Element on a Linked List
struct node* temp = head;
while(temp->next->next!=NULL){
temp = temp->next;
You can search an element on a linked list using a loop using the following steps. We are
finding item on a linked list.
Make head as the current node.
Run a loop until the current node is NULL because the last element points to NULL.
In each iteration, check if the key of the node is equal to item. If it the key matches the
item, return true otherwise return false.
Data Structure laboratory
Algorithm: -
1. Start
// Search a node
2. bool searchNode(struct Node** head_ref,
struct Node* current = *head_ref;
Conclusion:- Thus all operation of singly linked list have been implemented
while (current != NULL) {
Frequently Asked Questions:
if (current->data == key) return true;
current = current->next;
1. Elaborate the advantages of Linked List over sequential organization.
}
2. Discuss the applications of pointers with syntax. return false;
3. Analyze your program to find time complexity. }
4. Design any other real life application of linked list.
5. Compare array with linked list.
6. Analyze the space complexity of your program.
7. Justify that you always need to use structure while using linked list.
8. Elaborate the applications of linked list.
9. A linked list is dynamic data structure. The size of a linked list can be changed
dynamically (during execution). How does this feature benefit a programmer?
10. Elaborate the different ways to allocate memory dynamically with synta
Input-Output :
Data Structure laboratory
Experiment No. 8
Title: - C++ program to implement doubly linked lists
Aim: - Write C++ program for storing binary number using doubly linked lists. Write
functions-
a) To compute 1‘s and 2‘s complement
b) Add two binary numbers.
Software used:- C++
O.S: used 64-bit open source Linux
Theory: - Mapped to Course Objective:
A doubly linked list is a type of linked list in which each node consists of Data Structure laboratory
3 components:
*prev - address of the previous nodeTo learn and understand basic concepts of doubly linked list data structu
data - data item
*next - address of next node Mapped to Course Outcome:
After successfully performing this experiment, the studen
understand the implementation of doubly linked list data structure and
problem.
Representation of Doubly Linked List
struct node {
int data;
struct node *next;
struct node *prev;
}
Insertion on a Doubly Linked List
Pushing a node to a doubly-linked list is similar to pushing a node to a linked list, but extra
work is required to handle the pointer to the previous node.
We can insert elements at 3 different positions of a doubly-linked list:
1. Insertion at the beginning
2. Insertion in-between nodes
3. Insertion at the End
Suppose we have a double-linked list with elements 1, 2, and 3.
Data Structure laboratory
Insertion at the Beginning
Let's add a node with value 6 at the beginning of the doubly linked list we made above.
1. Create a new node
● allocate memory for newNode
● assign the data to newNode.
2. Set prev and next pointers of new node
● point next of newNode to the first node of the doubly linked list
● point prev to null
3. Make new node as head node
● Point prev of the first node to newNode (now the previous head is the second
node)
● Point head to newNode
Data Structure laboratory
2. Insertion in between two nodes
Let's add a node with value 6 after node with value 1 in the doubly linked list.
1. Create a new node
● allocate memory for newNode
● assign the data to newNode.
2. Set the next pointer of new node and previous node
● assign the value of next from previous node to the next of newNode
● assign the address of newNode to the next of previous node
3. Set the prev pointer of new node and the next node
● assign the value of prev of next node to the prev of newNode
● assign the address of newNode to the prev of next node
Data Structure laboratory
The final doubly linked list is after this insertion is:
3. Insertion at the End
Let's add a node with value 6 at the end of the doubly linked list.
1. Create a new node
2. Set prev and next pointers of new node and the previous node
If the linked list is empty, make the newNode as the head node. Otherwise,
traverse to the end of the doubly linked list and
Data Structure laboratory
Final doubly linked list
Algorithm:-
1. start
2. Read decimal number and convert in to binary
void binary::generateBinary(int no)
{
bool rem;
node *p;
rem=no%2;
start=new node(rem);
no=no/2;
while(no!=0)
{
rem=no%2;
no=no/2;
p=new node(rem);
p->next=start;
start->prev=p;
start=p;
}
}
3.
Data Structure laboratory
Conclusion:- Successfully implemented all Doubly linked list operations
Frequently Asked Questions:
1. Which data structure can able to construct with the help of doubly linked list?
2. What are the three fields of doubly linked list?
3. What is the time complexity of doubly linked list?
4. How many null pointers exist in a doubly linked list?
5. Can doubly linked list be linear or circular?
Experiment No. 9
Title: - C++ program to print reversed string and check whether given string is palindrome
or not.
Aim: - Write a program in C++ which implements class template and function
template.
A palindrome is a string of character that‘s the same forward and backward. Typically,
punctuation, capitalization, and spaces are ignored. For example, “Poor Dan is in a
droop” is a palindrome, as can be seen by examining the characters “poor danisina
droop” and observing that they are the same forward and backward. One way to check
for a palindrome is to reverse the characters in the string and then compare with them
the original-in a palindrome, the sequence will be identical. Write C++ program with
functions-
a) To print original string followed by reversed string using stack
Data Structure laboratory
b) To check whether given string is palindrome or not
Software used: - C++
O.S: used 64-bit open source Linux
Theory: -
Mapped to Course Objective:
Stack is a LIFO (Last In First Out) data structure. It allows us to insert and remove an
element in special order.
To learn
Stack allows element addition and removal and
from theunderstand basic concepts of stack data structure
top of stack
Mapped to Course Outcome:
After successfully performing this experiment, the student
understand the implementation of stack data structure and its use in re
Data Structure laboratory
Basic Stack Operations
• push() − Pushing (storing) an element on the stack.
• pop() − Removing (accessing) an element from the stack.
• peek() − get the top data element of the stack, without removing it.
• isFull() − check if stack is full.
• isEmpty() − check if stack is empty.
Algorithm:-
Algorithm for PUSH operation
Check if the stack is full or not.
If the stack is full,
then print error of overflow and exit the program.
If the stack is not full,
then increment the top and add the element.
POP operation
Check if the stack is empty or not.
If the stack is empty,
then print error of underflow and exit the program.
If the stack is not empty,
then print the element at the top and decrement the top. Data Structure laboratory
Read string and convert function
void str::convertstring()
{
int i,j=0;
char tempstr[25];
for(i=0;inputstr[i]!='\0';i++)
{
if(inputstr[i]>=97 && inputstr[i]<=122)
{
tempstr[j]=inputstr[i];
j++;
}
else if(inputstr[i]>=65 && inputstr[i]<=190)
{
tempstr[j]=inputstr[i]+32;
j++;
}
}
tempstr[j]='\0';
strcpy(inputstr,tempstr);
cout<<"\n\nYour converted string:-> "<<inputstr;
String reverse function
void str::revstring()
{
int i;
char ch;
for(i=0;inputstr[i]!='\0';i++)
stobj.push(inputstr[i]);
i=0;
cout<<"\n\nAfter reverse your string:-> ";
while(!stobj.isempty())
{
ch=stobj.pop();
cout<<ch;
revstr[i]=ch;
i++;
}
Data Structure laboratory
}
Check String palindrome function
void str::checkpalindrome()
{
cout<<"\n\n\n\n\n";
cout<<"\nCheck for palindrome"<<endl;
readstring();
convertstring();
revstring();
if(strcmp(inputstr,revstr)==0)
cout<<"\n\nYour string is PALINDROME";
else
cout<<"\n\nYour string is NOT PALINDROME";
}
Conclusion:- Thus learned and implemented string operations using stack.
Frequently Asked Questions:
1. What are the 3 primary methods for a stack?
2. What is the main reason to use stack?
3. Why stack is called LIFO?
4. What are the limitations of stack?
5. Which data structure is used in stack?
6. Why stack is faster than heap?
Data Structure laboratory
Experiment No. 10
Title: - C++ program to check whether given expression is well parenthesized or not
Aim: - In any language program mostly syntax error occurs due to unbalancing
delimiter such as (),{},[]. Write C++ program using stack to check whether given
expression is well parenthesized or not.
Data Structure laboratory
Software used: - C++
O.S: used 64-bit open source Linux
Theory: -
A stack can be implemented by means of Array, Structure, Pointer and Linked-List. Stack can
either be a fixed size one or it may have aMapped
sense oftodynamic
Course Objective:
resizing. Here, we are going to
implement stack using arrays which makes it a fixed size stack implementation.
To learn and understand basic concepts of stack data structure
Basic Operations
Mapped to Course Outcome:
push() − pushing (storing) an element on the stack.
pop() − removing (accessing) After
an successfully
element from performing
the this experiment, the studen
stack.
understand the implementation of stack data structure and its use in
To use a stack efficiently we need to check status of stack through following functionality,
gettop() − get the top data element of the stack, without
removing it.
isFull() − check if stack is full.
isEmpty() − check if stack is empty.
The top pointer provides top value of the stack
without actually removing it. Algorithm of gettop( )
function –
begin procedure gettop
return stack[top]
end procedure
Algorithm of isfull( ) function −
#define MAXSIZE 10
Char stack[MAXSIZE];
begin procedure isfull
if top equals to MAXSIZE
return true
else
return false
endif
end procedure Data Structure laboratory
Algorithm of isempty( ) function
begin procedure isempty
if top less than 0
return true
else
return false
endif
end procedure
Algorithm for PUSH( ) operation
begin procedure push: stack, data
if stack is full
return null endif
top ← top + 1
stack[top]← data
end procedure
Algorithm for POP( ) operation
begin procedure pop: stack if stack
is empty
return null
endif
data ← stack[top]
top ← top - 1
return data
end procedure
Algorithm:
1. Declare a character stack S.
2. Now traverse the expression string exp.
a. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
b. b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack
and if the popped character is the matching starting bracket then fine else
parenthesis are not balanced.
3. After complete traversal, if there is some starting bracket left in stack then “not
balanced”
Conclusion: - Successfully implemented of stack to check the well-formedData
parentheses.
Structure laboratory
Frequently Asked Questions:
1. Compare stack with queue.
2. Analyze your program to find time complexity.
3. Design one real life application of stack.
4. Elaborate the stack implementation using array.
5. Analyze your program to find space complexity.
6. Elaborate the stack implementation using linked list.
7. Write the postfix form of the expression (a+(b*(c/d)-e))?
8. Elaborate the operation of stack.
9. Comment on the value of TOP=-1.
10. List the advantages of stack over queue.
Experiment No. 11
Title: - C++ program to implement queue and its operations.
Aim: - Queues are frequently used in computer programming, and a typical
example is the creation of a job queue by an operating system. If the operating system
does not use priorities, then the jobs are processed in the order they enter the system.
Write C++ program for simulating job queue. Write functions to add job and delete job
from queue..
Data Structure laboratory
Software used: - C++
O.S: used 64-bit open source Linux
Theory: - Mapped to Course Objective:
Queue is also an abstract data type or a linear data structure, in which the first element is
To learn
inserted from one end called REAR(also and understand
called basic
tail), and the concepts
deletion of of queue data
existing structure
element
takes place from the other end calledMapped
as FRONT(also
to Coursecalled head). This makes queue as
Outcome:
FIFO data structure, which means that element inserted first will also
After successfully be removed
performing first.
this experiment, the student wi
The process to add an element into queue is called Enqueue
the implementation anddata
of queue thestructure
processand
of removal
its use inof
real life problem
an element from queue is called Dequeue.
Basic Operations :
enQueue(value) - Inserting value into the queue
In a queue data structure, enQueue() is a function used to insert a new element into the
queue. In a queue, the new element is always inserted at rear position. The enQueue()
function takes one integer value as parameter and inserts that value into the queue. We can
use the following steps to insert an element into the queue...
Step 1: Check whether queue is FULL. (rear == SIZE-1)
Step 2: If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!" and terminate
the function.
Step 3: If it is NOT FULL, then increment rear value by one (rear++) and set queue[rear] =
value.
deQueue() - Deleting a value from the Queue
In a queue data structure, deQueue() is a function used to delete an element from the queue.
In a queue, the element is always deleted from front position. The deQueue() function does
not take any value as parameter. We can use the following steps to delete an element from
the queue...
Step 1: Check whether queue is EMPTY. (front == rear)
Data Structure laboratory
Step 2: If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not possible!!!" and
terminate the function.
Step 3: If it is NOT EMPTY, then increment the front value by one (front ++). Then display
queue[front] as deleted element. Then check whether both front and rear are equal (front ==
rear), if it TRUE, then set both front and rear to '-1' (front = rear = - 1).
Algorithm:
Algorithm : procedure isfull
if rear equals to MAXSIZE
return true
else
return false
endif
end procedure
Algorithm : procedure isempty
if front is less than MIN OR front is greater than rear
return true
else
return false
endif
end procedure
Algorithm : procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true end
procedure
Algorithm : procedure dequeue
if queue is empty
return underflow
end if
data = queue[front]
front ← front + 1
return true
end procedure Data Structure laboratory
Conclusion: - Successfully implemented of queue and its operation.
Frequently Asked Questions:
1. Elaborate FRONT and REAR in a queue.
2. Analyze your program to find time complexity.
3. Elaborate various operations of queue.
4. Elaborate Queue full and Queue empty condition.
5. Discover applications of queue.
6. Compare disadvantages of queue with stack.
7. Elaborate any real life application of queue.
8. Analyze your program to find space complexity.
9. Compare queue implementation using array and queue implementation using linked list.
10. Design any one function using queue implementation using linked list.
.
Experiment No. 12
Title: - C++ program to simulate Deque
Aim: - A double-ended queue (deque) is a linear list in which additions and
deletions may be made at either end. Obtain a data representation mapping a deque
into a one-dimensional array. Write C++ program to simulate deque with functions to
add and delete elements from either end of the deque.
Data Structure laboratory
Software used: - C++
O.S: used 64-bit open source Linux
Theory: - Mapped to Course Objective:
Deque (usually pronounced like "deck") is an irregular acronym of double-ended queue.
Double-ended queues are sequenceTo learn and understand
containers basicsizes
with dynamic concepts
that of
candouble-ended
be expandedqueue
or
contracted on both ends (either its front or its back).
Mapped to Course Outcome:
Operations of deque : After successfully performing this experiment, the student wi
1. Deque() creates a new deque that is
theempty. It needs no
implementation of parameters
double-endedand returns
queue an empty
data structure and its use in re
deque.
2. addFront(item) adds a new item to the front of the deque. It needs the item and returns
nothing.
3. addRear(item) adds a new item to the rear of the deque. It needs the item andreturns
nothing.
4. removeFront() removes the front item from the deque. It needs no parameters and returns
the item. The deque is modified.
5. removeRear() removes the rear item from the deque. It needs no parameters and returns
the item. The deque is modified.
6. isEmpty() tests to see whether the deque is empty. It needs no parameters and returns a
boolean value.
7. size() returns the number of items in the deque. It needs no parameters and returns an
integer.
Algorithm:
Algorithm to add an element into DeQueue : Data Structure laboratory
Assumptions: pointer f,r and initial values are -1,-1
Q[] is an array
max represent the size of a queue
enq_front
step1. Start
step2. Check the queue is full or not as if (f <>
step3. If false update the pointer f as f= f-1
step4. Insert the element at pointer f as Q[f] = element
step5. Stop
enq_back
step1. Start
step2. Check the queue is full or not as if (r == max-1) if yes queue is full step3. If false
update the pointer r as r= r+1
step4. Insert the element at pointer r as Q[r] = element
step5. Stop
Algorithm to delete an element from the DeQueue
deq_front
step1. Start
step2. Check the queue is empty or not as if (f == r) if yes queue is empty step3. If false
update pointer f as f = f+1 and delete element at position f as element = Q[f] step4. If (f== r)
reset pointer f and r as f=r=-1
step5. Stop
deq_back
step1. Start
step2. Check the queue is empty or not as if (f == r) if yes queue is empty step3. If false
delete element at position r as element = Q[r]
step4. Update pointer r as r = r-1
step5. If (f == r) reset pointer f and r as f = r= -1
step6. Stop
Conclusion: - Successfully implemented double-ended queue and itsData
operation
Structure laboratory
Frequently Asked Questions:
1. Why double-ended queue is used?
2. How many operations are possible in double-ended queue?
3. Is double-ended queue a circular queue?
4. Which queue allows insertion and deletion at both ends?
5. What is input restricted double-ended queue?
1.
Experiment No. 13
Title: - C++ program to simulate the system using circular queue using array.
Aim: - Pizza parlor accepting maximum M orders. Orders are served in first come first
served basis. Order once placed cannot be cancelled. Write C++ program to simulate
the system using circular queue using array.
Data Structure laboratory
Software used: - C++
O.S: used 64-bit open source Linux
Theory: - Mapped to Course Objective:
A circular queue is the extended version of a regular queue where the last element is
connected to the first element. ThusTo learn and
forming understand
a circle-like basic concepts of Circular queue
structure.
Mapped to Course Outcome:
After successfully performing this experiment, the student wi
the implementation of circular queue data structure using array
The circular queue solves the major limitation of the normal queue. In a normal queue, after a
bit of insertion and deletion, there will be non-usable empty space.
How Circular Queue Works
Circular Queue works by the process of circular increment i.e. when we try to increment the
pointer and we reach the end of the queue, we start from the beginning of the queue.
Here, the circular increment is performed by modulo division with the queue size.
if REAR + 1 == 5 (overflow!), REAR = (REAR + 1)%5 = 0 (start of queue)
Circular Queue Operations
The circular queue work as follows:
● two pointers FRONT and REAR
● FRONT track the first element of the queue
● REAR track the last elements of the queue
● initially, set value of FRONT and REAR to -1
1. Enqueue Operation
● check if the queue is full
● for the first element, set value of FRONT to 0 Data Structure laboratory
● circularly increase the REAR index by 1 (i.e. if the rear reaches the end, next it would
be at the start of the queue)
● add the new element in the position pointed to by REAR
2. Dequeue Operation
● check if the queue is empty
● return the value pointed by FRONT
● circularly increase the FRONT index by 1
● for the last element, reset the values of FRONT and REAR to -1
However, the check for full queue has a new additional case:
Case 1: FRONT = 0 && REAR == SIZE - 1
Case 2: FRONT = REAR + 1
The second case happens when REAR starts from 0 due to circular increment and when
its value is just 1 less than FRONT, the queue is full.
Data Structure laboratory
Enque and Deque Operations
Algorithm:
Enqueue(x) Operation
Step 1: Check if the queue is full (Rear + 1 % Maxsize = Front)
Step 2: If the queue is full, there will be an Overflow error
Step 3: Check if the queue is empty, and set both Front and Rear to 0
Step 4: If Rear = Maxsize - 1 & Front != 0 (rear pointer is at the end of the queue and
front is not at 0th index), then set Rear = 0
Step 5: Otherwise, set Rear = (Rear + 1) % Maxsize
Step 6: Insert the element into the queue (Queue[Rear] = x)
Step 7: Exit
Dequeue() Operation
Step 1: Check if the queue is empty (Front = -1 & Rear = -1)
Step 2: If the queue is empty, Underflow error
Step 3: Set Element = Queue[Front]
Step 4: If there is only one element in a queue, set both Front and Rear to -1 (IF Front
= Rear, set Front = Rear = -1)
Step 5: And if Front = Maxsize -1 set Front = 0 Data Structure laboratory
Step 6: Otherwise, set Front = Front + 1
Step 7: Exit
Conclusion: - Successfully implemented circular queue using array
Frequently Asked Questions:
1. What is the main purpose of using a circular queue?
2. How do you determine the size of a circular queue?
3. Is circular queue better than linear queue?
4. Does circular queue follow FIFO?
5. How do you check if a queue is empty or not?
Data Structure laboratory