DSL
DSL
SE COMPUTER ENGINEERING
LAB MANUAL
DATA STRUCTURE
LABORATORY
Prepared By
Prof. Vidya S Y
Lab Manual
The instructor„s manual is to be developed as a hands-on resource and reference. The instructor's
manual need to include prologue (about University/program/ institute/ department/foreword/ preface
etc), University syllabus, conduction & Assessment guidelines, topics under consideration- concept,
objectives, outcomes, set of typical applications/practicals/ guidelines, and references.
The laboratory practicals are to be submitted by student in the form of journal. Journal consists of
prologue, Certificate, table of contents, and handwritten write-up of each practical (Title,
Objectives, Problem Statement, Outcomes, software & Hardware requirements, Date of
Completion, Assessment grade/marks and assessor's sign, Theory- Concept in brief, algorithm,
flowchart, test cases, conclusion/analysis. Program codes with sample output of all perform
practical‟s are to be submitted as softcopy.
As a conscious effort and little contribution towards Green IT and environment awareness, attaching
printed papers as part of write-ups and program listing to journal may be avoided. Use of DVD
containing students programs maintained by lab In-charge is highly encouraged. For reference one or
two journals may be maintained with program prints at Laboratory.
Continuous assessment of laboratory work is done based on overall performance and lab practicals
performance of student. Each lab practical assessment will assign grade/marks based on parameters
with appropriate weightage. Suggested parameters for overall assessment as well as each lab practical
assessment include- timely completion, performance, innovation, efficient codes, punctuality and
neatness.
Both internal and external examiners should jointly set problem statements. During practical
assessment, the expert evaluator should give the maximum weightage to the satisfactory
implementation of the problem statement. The supplementary and relevant questions may be asked at
the time of evaluation to test the students for advanced learning, understanding of the fundamentals,
effective and efficient implementation. So encouraging efforts, transparent evaluation and fair
approach of the evaluator will not create any uncertainty or doubt in the minds of the students. So
adhering to these principles will consummate our team efforts to the promising start of the student's
academics.
The instructor is expected to frame the practicals by understanding the prerequisites, technological
aspects, utility and recent trends related to the topic. The practical framing policy need to address the
average students and inclusive of an element to attract and promote the intelligent students. The
instructor may set multiple sets of practicals and distribute among batches of students. It is
appreciated if the practicals are based on real world problems/applications. Encourage students for
appropriate use of Hungarian notation, proper indentation and comments. Use of open source
software is to be encouraged.
In addition to these, instructor may assign one real life application in the form of a mini- project based
on the concepts learned. Instructor may also set one practical or mini-project that is suitable to
respective branch beyond the scope of syllabus.
Set of suggested practical list is provided in groups- A, B, C, D, and E. Each student must perform at
least 13 practicals as at least 3 from group A, 3 from group B, 2 from group C, 2 from group D and
3 from group E.
Group A and B assignments should be implemented in Python without using built-in methods for
major functionality of assignment. Use List data structure of Python as array. Group C, D and E
assignments should be implemented in C++ language.
GROUP - B
B-11) a) Write a Python program to store roll numbers of student in array who attended
training program in random order. Write function for searching whether particular student
attended training program or not, using Linear search and Sentinel search.
5 a) Write a Python program to store roll numbers of student array who attended training
program in sorted order. Write function for searching whether particular student attended
training program or not, using Binary search and Fibonacci search
B-14) 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
6 a) Selection Sort
b) Bubble sort and display top five scores.
B-16) Write a Python program to store first year percentage of students in array. Write
7 function for sorting array of floating-point numbers in ascending order using quick sort
and display top five scores.
GROUP - C
C-19) 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
8 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
Two linked lists exists for two divisions. Concatenate two lists.
C-20) The ticket booking system of Cinemax theater has to be implemented using C++
program. There are 10 rows and 7 seats in each row. Doubly circular linked list has to be
maintained to keep track of free seats at rows. Assume some random booking to start with.
Use array to store pointers (Head pointer) to each row. On demand
9 a) The list of available seats is to be displayed
b) The seats are to be booked
The booking can be cancelled.
C-21) Write C++ program for storing appointment schedule for day. Appointments are
booked randomly using linked list. Set start and end time and min and max duration for
visit slot. Write functions for-
A) Display free slots
10 B) Book appointment
C) Sort list based on time
D) Cancel appointment ( check validity, time bounds, availability)
Sort list based on time using pointer manipulation
GROUP – D
D-26) In any language program mostly syntax error occurs due to unbalancing delimiter
11 such as (),{},[]. Write C++ program using stack to check whether given expression is well
parenthesized or not.
D-27) Implement C++ program for expression conversion as infix to postfix and
its evaluation using stack based on given conditions:
1. Operands and operator, both must be single character.
12
2. Input Postfix expression must be in a desired format.
Only '+', '-', '*' and '/ ' operators are expected.
GROUP – E
E-29) 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
13 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.
E-31) 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-
14 dimensional array. Write C++ program to simulate deque with functions to add and
delete elements from either end of the deque.
Aim: -
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.
(Note- Do not use SET built-in functions)
Prerequisite:
Python Programming
Objectives:
To understand implementation of Array data structure.
Understand the implementation of set with various operations like, Union, Intersection and
Difference etc.
Input:
N number of students.
Outcome:
Theory- Concept:
What is array?
Whenever we want to work with large number of data values, we need to use that much
number of different variables. As the numbers of variables are increasing, complexity of
the program also increases and programmers get confused with the variable names.
There may be situations in which we need to work with large number of similar data
values. To make this work more easily, C programming language provides a concept
called "Array"
An array is a variable which can store multiple values of same data type at a time.
An array can also be defined as follows... "Collection of similar data items stored in
continuous memory locations with single name". To understand the concept of arrays,
consider the following
example declaration. int a, b, c;
Here, the compiler allocates 2 bytes of memory with name 'a', another 2 bytes of memory
with name 'b' and more 2 bytes with name 'c'. These three memory locations are may be
in sequence or may not be in sequence. Here these individual variables can store only
one value at a time.
That means all these three memory locations are named as 'a'. But "how can we refer
individual elements?" is the big question. Answer for this question is, compiler not only
allocates memory, but also assigns a numerical value to each individual element of an
array. This numerical value is called as "Index". Index values for the above example are
as follows...
The individual elements of an array are identified using the combination of 'name' and
'index' as follows...
arrayName [ indexValue ]
For the above example the individual elements can be referred to as follows...
If I want to assign a value to any of these memory locations (array elements), we can
assign as follows...
a[1] = 100;
The result will be as follows..
Sets in Python:
Set Operations:
Sets
Creating a set
Sets are created using the flower braces but instead of adding key-value pairs, you just pass
values to it.
Output:
{1, 2, 3, 4, 5}
Adding elements
To add elements, you use the add() function and pass the value to it.
1 my_set = {1, 2, 3}
2 my_set.add(4) #add element to set
3 print(my_set)
Output:
{1, 2, 3, 4}
Operations in sets
The different operations on set such as union, intersection and so on are shown below.
1 my_set = {1, 2, 3, 4}
2 my_set_2 = {3, 4, 5, 6}
3 print(my_set.union(my_set_2), ' ', my_set | my_set_2)
4 print(my_set.intersection(my_set_2), ' ', my_set & my_set_2)
5 print(my_set.difference(my_set_2), ' ', my_set - my_set_2)
6 print(my_set.symmetric_difference(my_set_2), ' ', my_set ^ my_set_2)
7 my_set.clear()
8 print(my_set)
Output:
{1, 2, 3, 4, 5, 6} ———- {1, 2, 3, 4, 5, 6}
{3, 4} ———- {3, 4}
{1, 2} ———- {1, 2}
{1, 2, 5, 6} ———- {1, 2, 5, 6}
set()
1. Union
For sets A, B, their union A U B is the set containing all elements that are
either in A, or (“Ú”) in B (or, of course, in both).
Example if set A= {2,3,5} and set B= {3,5,7} then, A U B = { 2,3,5,7 }
2. Intersection
For sets A, B, their intersection A^B is the set containing all elements that
are simultaneously in A and (“^”) in B.
Example if set A= {2,3,5} and set B= {3,5,7} then, A ^ B = { 3,5 }
3. Difference
For sets A, B, the difference of A and B, written A-B, is the set of all
elements that are in A but not B.
Example- if set A= {2,3,5} and set B= {3,5,7} then, A - B = { 2 }
Implementation:
a = '''
In second year computer engineering class, group A student’s play cricket, group B students play
badminton and group C students play football.\n
Write a python program using functions to compute following: - \n
a)\tList of students who play both cricket and badminton \n
b) \tList of students who play either cricket or badminton but not both \n
c) \tNumber of students who play neither cricket nor badminton\n
d) \tNumber of students who play cricket and football but not badminton.\n
'''
print(a)
print("GroupA=",groupA)
print("GroupB=",groupB)
print("GroupC=",groupC)
for i in range(lena):
for j in range (lenb):
if(groupA[i]==groupB[j]):
newlist.append(groupA[i])
break
print("List of students who play both cricket and badminton")
print(newlist)
for i in range(lenb):
for j in range(lena):
if(groupB[i]==groupA[j]):
flag=1
break;
if(flag==0):
newlist.append(groupB[i])
flag=0
print("List of students who play either cricket or badminton but not both")
print(newlist)
newlist=[]
lena=len(groupA)
lenb=len(groupB)
lenc=len(groupC)
flag=0
for i in range(lenc):
for j in range(lena):
if(groupC[i]==groupA[j]):
flag=1
break
for var in range(lenb):
if(groupC[i]==groupB[var]):
flag=1
break
if(flag==0):
newlist.append(groupC[i])
flag=0
def fourth(groupA,groupB,groupC):
list1=[]
newlist = []
lena = len(groupA)
lenb = len(groupB)
lenc = len(groupC)
flag=0
for i in range(lena):
for j in range(lenc):
if(groupA[i]==groupC[j]):
list1.append(groupA[i])
break
newl=len(list1)
for i in range(newl):
for j in range(lenb):
if(list1[i]==groupB[j]):
flag=1
break
if(flag==0):
newlist.append(list1[i])
flag=0
print("Number of students who play cricket and football but not badminton")
print(newlist)
first(groupA,groupB)
second(groupA,groupB)
third(groupA,groupB,groupC)
fourth(groupA,groupB,groupC)
Conclusion:
Hence, we have learned the Array Data structure and how to use it to implement
Set Operations.
Questions:
1. What is Data structure?
2. What are the different types of Data Structure based on organizing method?
3. Explain Array is of which type of Data Structure?
4. What are different types array? 5. What is an Algorithm?
Prerequisite:
• Python Programming
Objectives:
To understand the use functions for N students record.
Lists are great to use when you want to work with many related values. They enable you to
keep data together that belongs together, condense your code, and perform the same
methods and operations on multiple values at once.
When thinking about Python lists and other data structures that are types of collections, it
is useful to consider all the different collections you have on your computer: your
assortment of files, your song playlists, your browser bookmarks, your emails, the
collection of videos you can access on a streaming service, and more.
To get started, let’s create a list that contains items of the string data type:
When we print out the list, the output looks exactly like the list we created:
print(sea_creatures)
Indexing Lists:
Each item in a list corresponds to an index number, which is an integer value, starting
with the index number 0.
For the list sea_creatures, the index breakdown looks like this:
0 1 2 3 4
Dictionary
Dictionaries are used to store key-value pairs. To understand better, think of a phone directory
where hundreds and thousands of names and their corresponding numbers have been added.
Now the constant values here are Name and the Phone Numbers which are called as the keys.
And the various names and phone numbers are the values that have been fed to the keys. If you
access the values of the keys, you will obtain all the names and phone numbers. So that is what
a key-value pair is. And in Python, this structure is stored using Dictionaries. Let us understand
this better with an example program.
Creating a Dictionary
Dictionaries can be created using the flower braces or using the dict() function. You need to
add the key-value pairs whenever you work with dictionaries.
Output: {}
{1: ‘Python’, 2: ‘Java’}
Tuple: Tuples are the same as lists are with the exception that the data once entered into the tuple
cannot be changed no matter what. The only exception is when the data inside the tuple is
mutable, only then the tuple data can be changed. The example program will help you
understand better.
Creating a Tuple:
You create a tuple using parenthesis or using the tuple() function.
Sets are a collection of unordered elements that are unique. Meaning that even if the data is
repeated more than one time, it would be entered into the set only once. It resembles the sets
that you have learnt in arithmetic. The operations also are the same as is with the arithmetic
sets. An example program would help you understand better.
Creating a set
Sets are created using the flower braces but instead of adding key-value pairs, you just pass
values to it.
Output:
{1, 2, 3, 4, 5}
Functions Used :
Write algorithm/pseudo code for each function.
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
def accept():
fds=[]
n=int(input("Enter the Student count of class:"))
for i in range(n):
print("Enter the marks scored in FDS for student %i: "%(i+1))
var=int(input())
fds.append(var)
print("\n1. Marks stored in fds:")
for i in range(n):
print("Student %i:"%(i+1),fds[i])
return fds
def average(fds):
sum=0
for i in range(len(fds)):
if(fds[i]!=-1):
sum=sum+fds[i]
avg=sum/len(fds)
def highlow(fds):
print("3. Highest score and lowest score of class:")
large=fds[0]
for i in range(len(fds)):
if(large<fds[i]):
large=fds[i]
print("Highest marks of class:",large)
def absent(fds):
count=0
print("4. Count of students who were absent for the test: ")
for i in range(len(fds)):
if(fds[i]==-1):
count=count+1
print("Absent Student roll is :%i"%(i+1))
def highfre(fds):
max1=0
for i in range(len(fds)):
if(fds[i]!=-1):
var=fds.count(fds[i])
if(var>max1):
max1=var
res=fds[i]
while True:
Conclusion:
Hence, we have learned and understand the data structures in python.
A P J Total
Dated Sign
3 4 3 10
Questions:
1. Basics of python Programming.
2. What are functions?
3. What are the features of python Programming?
4. What are array?
Objectives:
• To understand the use standard library functions for
string operations.
Theory :
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
Hello How to
Hello access
Hello
Hello, welcome to
the world of Python
characters in a string?
We can access individual characters using indexing and a range of characters using
slicing. Index starts from 0. Trying to access a character out of index range will raise
an IndexError. The index must be an integer. We can't use floats or other types, this will
result into TypeError.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access
a range of items in a string by using the slicing operator :(colon).
#first character
print('str[0] = ', str[0])
#last character
Data Structure and Lab (DSL) SE Computer Engineering
def one():
def two():
str1=input("Enter the string:")
char=input("Enter character")
print(str1)
counter=0
for i in range(len(str1)):
if char==str1[i]:
counter+=1 #counter=counter+1
def three():
str2 = input("Enter string")
lenstr2=len(str2)
j=lenstr2-1
flag=0
for i in range(int (lenstr2/2+1)):
if(str2[i]==str2[j]):
flag=1
else:
break
j=-1
if(flag==1):
print("It is palindrome")
else:
print("it is not palindrome")
def four():
str1 = input("Enter the string:") #i am ganesh 11
sub1=input("Enter substring:") #ane
sublen=len(sub1) //3
index1=0
j=0
for i in range(len(str1)):
if(sub1[j]==str1[i]):
j=j+1
if(j==sublen):
index1=i-(sublen-1)
break
else:
j=0
def five():
str1 = input("Enter input string:")
list1= str1.split()
list2=set(list1) #Delete duplicates \n", \
list3=list(list2) #convert set again into List\n", \
print(list1)
print(list3)
list4=[]
list5=[]
counter=0
for i in range(len(list3)):
counter=0
for j in range(len(list1)):
if(list3[i]==list1[j]):
counter+=1
list4=list3[i],counter
list5.append(list4)
print(list5)
while True:
ch=int(input("Enter your choice:"))
if(ch==1):
one()
elif(ch==2):
two()
elif(ch==3):
three()
elif(ch==4):
four()
elif(ch==5):
five()
elif(ch==6):
break
Conclusion:
Hence, we studied and implemented String operation in Python.
A P J Total
Dated Sign
3 4 3 10
Questions:
1. Write a program to find the length of string.
2. Write a program to display string from backward.
3. Write a program to count number of words in string.
4. Write a program to concatenate one string contents to another.
5. Write a program to compare two strings they are exact equal or not.
6. Write a program to check a string is palindrome or not.
7. WAP to find a substring within a string. If found display its starting position.
8. Write a program to reverse a string.
9. Write a program to convert a string in lowercase.
10. Write a program to convert a string in uppercase.
Practical No : 04 (A)
Practical Title: Python program that computes the net amount of a bank account.
Aim :
A-4 Write a Python program that computes the net amount of a bank account based a
transaction log from console input. The transaction log format is shown as following: D 100
W 200 (Withdrawal is not allowed if balance is going negative. Write functions for withdraw
and deposit) D means deposit while W means withdrawal.
Suppose the following input is supplied to the program:
D 300, D 300 , W 200, D 100 Then, the output should be: 500
Pre-requisite:
Knowledge of representing function in Python
Objectives:
Input :
Input is supplied to the program:
D 300, D 300 , W 200, D 100 Then, the output should be: 500
Outcome:
D 300, D 300 , W 200, D 100 Then, the output should be: 500
Theory:
Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable.
Syntax of Function
def function_name(parameters):
Above shown is a function definition that consists of the following components.
How to
def greet(name):
call a
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
function in python?
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.
>>> greet('Paul')
Hello, Paul. Good morning!
Note: Try running the above code in the Python program with the function definition to see the
output.
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
greet('Paul')
The return statement is used to exit a function and go back to the place from where it was called.
Syntax of return
>>> print(greet("May"))
Hello, May. Good morning!
None
Here, is the returned value since directly prints the name and no statement
None greet() return
is used.
Example of return
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
Output
Types of Functions
2
Basically,
4 we can divide functions into the following two types:
print( '''
Write a python program that computes the net amount of a bank account based a transaction
log from console input.
The transaction log format is shown as following:
D 100 W 200 (Withdrawal is not allowed if balance is going negative. Write functions for
withdraw and deposit) D means deposit while W means withdrawal.
Suppose the following input is supplied to the program:
D 300 , D 300 , W 200 , D 100 ,
Then, the output should be: 500
''')
def deposit(num):
global balance
balance =balance+num
def withdrawal(num):
global balance
if(balance >0):
balance=balance-num
else:
print("Withdraw not possible because balance is less.")
list1 = []
balance=0
while True:
data = input("Please enter the transaction details:")
if ('Exit' == data):
break
list1.append(data.split())
print(list1)
print("Balance =",balance)
Conclusion:
Hence, we studied, how to use functions in python programming.
A P J Total
Dated Sign
3 4 3 10
GROUP - B
Aim : B-11) a) Write a Python program to store roll numbers of student in array who attended training
program in random order. Write function for searching whether particular student attended training
program or not, using Linear search and Sentinel search.
b) Write a Python program to store roll numbers of student array who attended training
program in sorted order. Write function for searching whether particular student attended training
program or not, using Binary search and Fibonacci search
Pre-requisite:
Knowledge of Fibonacci series, and basic searching concepts.
Objectives:
• To search record using linear, binary and sentinel searching.
Input:
Output:
If Searched Sufessfully then function returns index of searched key otherwise return “Search key not
present in the list”
Theory:
1. Linear Search:
In computer science, a linear search or sequential search is a method for finding an element within
a list. It sequentially checks each element of the list until a match is found or the whole list has been
searched.
A simple approach is to do a linear search, i.e
Start from the leftmost element of arr[] and one by one compare x with each element of
arr[]
If x matches with an element, return the index.
If x doesn’t match with any of elements, return -1.
Pseudocode
end procedure
Complexity of algorithm
Complexity Best Case Average Case Worst Case
Space O(1)
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
m=linearsearch(arr,x)
if(m==-1):
else:
printf(“”)
Linear Search : The idea behind linear search is to compare the search item with the elements in the
list one by one (using a loop) and stop as soon as we get the first copy of the search element in the list.
Now considering the worst case in which the search element does not exist in the list of size N then
the Simple Linear Search will take a total of 2N+1 comparisons (N comparisons against every
element in the search list and N+1 comparisons to test against the end of the loop condition).
Sentinel Linear Search : Here the idea is to reduce the number of comparisons required to find an
element in a list. Here we replace the last element of the list with the search element itself and run
a while loop to see if there exists any copy of the search element in the list and quit the loop as soon
as we find the search element. See the code snippet for clarification.
15 30 10 7 8 9
0 1 2 3 4 5
X=12
I=5
Last=a[n-1]=9
( N comparisons in the while loop and 2 comparisons in the if condition). Which is better than
( 2N+1 ) comparisons as found in Simple Linear Search.
Take note that both the algorithms have time complexity of O(n).
3. Binary Search
Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].
A simple approach is to do linear search. The time complexity of above algorithm is O(n). Another
approach to perform the same task is using Binary Search.
Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with
an interval covering the whole array. If the value of the search key is less than the item in the middle
of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half.
Repeatedly check until the value is found or the interval is empty.
Example :
The idea of binary search is to use the information that the array is sorted and reduce the time
complexity to O(Log n).
5. low = 0
6. high = len(list1) - 1
7. mid = 0
8.
9. while low <= high:
10. # for get integer result
11. mid = (high + low) // 2
12.
13. # Check if n is present at mid
14. if list1[mid] < n:
15. low = mid + 1
16.
17. # If n is greater, compare to the right of mid
18. elif list1[mid] > n:
19. high = mid - 1
20.
21. # If n is smaller, compared to the left of mid
22. else:
23. return mid
24.
25. # element was not present in the list, return -1
26. return -1
27.
28.
29. # Initial list1
30. list1 = [12, 24, 32, 39, 45, 50, 54]
31. n = 45
32.
33. # Function call
34. result = binary_search(list1, n)
35.
36. if result != -1:
37. print("Element is present at index", str(result))
38. else:
39. print("Element is not present in list1")
Output:
=> n = 2k
Applying log function on both sides:
=> log2 (n) = log2 (2k)
=> log2 (n) = k log2 (2)
As (loga (a) = 1)
Therefore,
=> k = log2 (n)
Hence, the time complexity of Binary Search is
log2 (n)
Worst Case & Average Case time Complexity: log2(n)
Best case: O(1)
4. Fibonacci Search:
Given a sorted array arr[] of size n and an element x to be searched in it. Return index of x if it is
present in array else return -1.
Examples:
Input: arr[] = {2, 3, 4, 10, 40}, x = 10
Output: 3
Element x is present at index 3.
Algorithm:
Algorithm Steps:
1. Find the smallest Fibonacci Number greater than or equal to n. Let this number be fibM
[m’th Fibonacci Number]. Let the two Fibonacci numbers preceding it be fibMm1 [(m-
1)’th Fibonacci Number] and fibMm2 [(m-2)’th Fibonacci Number].
2. While the array has elements to be inspected:
1. Compare x with the last element of the range covered by fibMm2
2. If x matches, return index
3. Else If x is less than the element, move the three Fibonacci variables two
Fibonacci down, indicating elimination of approximately rear two-third of the
remaining array.
4. Else x is greater than the element, move the three Fibonacci variables one
Fibonacci down. Reset offset to index. Together these indicate the elimination
of approximately front one-third of the remaining array.
Example:
15 25 27 38 45 85 110
0 1 2 3 4 5 6
i=m2+offset==== 3
M=5,m1=3, m2=2
m=m1; m1=m2; m2=m-m1
Offset=m2=3
Complexity:
Worse Case Time Complexity: O(logn)
Conclusion:
Hence, e Studied Linear Search, Binary Search, Fibonacci Search, Sentinel Search
A P J Total
Dated Sign
3 4 3 10
Practical No:06(B)
Practical Title: Sorting of an array using selection and bubble 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 order using
a) Selection Sort
b) Bubble sort and display top five scores.of club.
Pre-requisite:
Objective:
To sort array of floating point numbers in ascending order using Selection Sort b) Bubble
sort and
Display top five scores.
Input:
Size of array Elements of array
Theory :
Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange
data in a particular order. Most common orders are in numerical or lexicographical order.
The importance of sorting lies in the fact that data searching can be optimized to a very high level, if
data is stored in a sorted manner.
Sorting is also used to represent data in more readable formats.
Following are some of the examples of sorting in real-life scenarios −
Telephone Directory − The telephone directory stores the telephone numbers of people sorted
by their names, so that the names can be searched easily.
Dictionary − The dictionary stores words in an alphabetical order so that searching of any
word becomes easy.
Internal and External Sorting:
An internal sort is any data sorting process that takes place entirely within the main memory of a
computer. This is possible whenever the data to be sorted is small enough to all be held in the main
memory.
Some common internal sorting algorithms include:
1. Bubble Sort
2. Insertion Sort
3. Quick Sort
4. Heap Sort
5. Radix Sort
6. Selection sort
External sorting is a class of sorting algorithms that can handle massive amounts of data. External
sorting is required when the data being sorted do not fit into the main memory of a computing device
(usually RAM) and instead they must reside in the slower external memory.
Example: Merge Sort
Comparison Based Sorting:
1. Bubble Sort
2. Selection sort
3. Merge Sort
4. Insertion Sort
5. Quick Sort
6. Shell Sort
Examples:
If the elements are n then n-1 passes are required to sort the bubble sort.
ass 1
15 7 9 25 -3 7
Step1 7 15 9 25 -3 7
Step2 7 9 15 25 -3 7
Step3 7 9 15 25 -3 7
Step4 7 9 15 -3 25 7
Step5 7 9 15 -3 7 25
Pass 2 0 1 2 3 4 5
7 9 15 -3 7 25
Step1 7 9 15 -3 7 25
Step2 7 9 15 -3 7 25
Step3 7 9 -3 15 7 25
Step4 7 9 -3 7 15 25
Pass 3 0 1 2 3 4 5
7 9 -3 7 15 25
Step1 7 9 -3 7 15 25
Step2 7 -3 9 7 15 25
Step3 7 -3 7 9 15 25
Pass 4 0 1 2 3 4 5
7 -3 7 9 15 25
Step1 -3 7 7 9 15 25
Step2 -3 7 7 9 15 25
Pass 5 0 1 2 3 4 5
-3 7 7 9 15 25
Step1 -3 7 7 9 15 25
2. Selection Sort:
- in place comparison sorting.
- Record is divided into two subparts:
1. Sorted record
2. Un sorted
- We select the smallest element from the record and place it at the beginning of the record.
- Initially sorted subarray is empty, whole list/ record is unsorted subarray.
Step6 -8 18 5 7 0 20 3
Pass2 -8 18 5 7 0 20 3
Step1 -8 5 18 7 0 20 3
Step2 -8 5 18 7 0 20 3
Step3 -8 0 18 7 5 20 3
Step4 -8 0 18 7 5 20 3
Step5 -8 0 18 7 5 20 3
Pass3 -8 0 18 7 5 20 3
Step1 -8 0 7 18 5 20 3
Step2 -8 0 5 18 7 20 3
Step3 -8 0 5 18 7 20 3
Step4 -8 0 3 18 7 20 5
Pass4 -8 0 3 18 7 20 5
Step1 -8 0 3 7 18 20 5
Step2 -8 0 3 7 18 20 5
Step3 -8 0 3 5 18 20 7
Pass5 -8 0 3 5 18 20 7
Step1 -8 0 3 5 18 20 7
Step2 -8 0 3 5 7 20 18
Pass6 -8 0 3 5 7 20 18
Step1 -8 0 3 5 7 18 20
Analysis: n
=(n-1)+(n-2)+(n-3)+……+3+2+1
=n(n-1)/2 =(n^2-n)/2 = O(n2)
Best, Average, Worse : O(n^2)
Algorithm
We assume list is an array of n elements. We further assume that swap function swaps the values of
the given array elements.
begin BubbleSort(list)
return list
end BubbleSort
selectionSort(array, size)
end selectionSort
Flowchart:
Conclusion:
Hence, we studied sorting of an array using selection and bubble sort.
A P J Total
Dated Sign
3 4 3 10
Question Bank:
Practical No:07(B)
Practical Title: Sorting array of floating-point numbers in ascending order using 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 order using quick sort and
display top five scores.
Pre-requisite:
Objective:
• To sort array using quick sort
Theory :
Examples:
0 1 2 3 4 5 6 7 8
a 25 9 11 21 95 0 17 5 32
P=0,i=0, j=8 h=0,h=8
a[i]<=a[p] i++ if[j]>a[p] j—
if(i<j) swap I and j
if I and j cross
then swap p with j
0 1 2 3 4 5 6 7 8
17 9 11 21 5 0 25 j 95 32
i
a(l,j-1) a(j+1,h)
Complexity of Quicksort:
Worst Case: The worst case occurs when the partition process always picks greatest or smallest
element as pivot. If we consider above partition strategy where last element is always picked as
pivot, the worst case would occur when the array is already sorted in increasing or decreasing
order. Following is recurrence for worst case.
T(n) = T(0) + T(n-1) + (n)
which is equivalent to
Best Case: The best case occurs when the partition process always picks the middle element as
pivot. Following is recurrence for best case.
T(n) = 2T(n/2) + (n)
The solution of above recurrence is O(nLogn).
Average Case:
To do average case analysis, we need to consider all possible permutation of array and calculate
time taken by every permutation which doesn’t look easy.
We can get an idea of average case by considering the case when partition puts O(n/9) elements in
one set and O(9n/10) elements in other set. Following is recurrence for this case.
T(n) = T(n/9) + T(9n/10) + (n)
Solution of above recurrence is also O(nLogn)
n = len(arr)
quickSort(arr, 0, n-1)
print("Sorted array is:")
for i in range(n):
print("%d" % arr[i]),
Conclusion:
Hence We Studied Quick Sort algorithm with examples.
A P J Total
Dated Sign
3 4 3 10
Question Bank:
1. Explain the sorting?
2. What are the different types of sorts in data structures?
3.Define the quick sort?
5. How many passes are
required in quick sort? 6.What
is the time complexity of quick
sort?
GROUP -
C
Practical No : 08 (C)
Assignment Title: Write C++ program to maintain club member ‘s information using
singly linked list.
Aim: Department of Computer Engineering has student's 1/8 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) Display list in reverse order using recursion
e) Two linked lists exist for two divisions. Concatenate two lists
Theory:
Linked List :
A linked list is a linear data structure, in which the elements are not stored at contiguous memory
locations. The elements in a linked list are linked using pointers as shown in the below image:
In simple words, a linked list consists of nodes where each node contains a data field and a
reference(link) to the next node in the list.
TYPES OF LINKED LIST:
There are 3 different implementations of Linked List available, they are:
1. Linear/Singly Linked List
2. Doubly Linked List
3. Circular Linked List
1. Linear/Singly Linked List:
• The first node is called the head; it points to the first node of the list and helps us access
every other element in the list. The last node, also sometimes called the tail, points
to NULL which helps us in determining when the list ends.
Primitive Operation performed on Singly Linked List:
Create:
Traverse:
Search:
Insert:
Delete:
Sort:
Concatenation:
No Memory Wastage
As size of linked list can increase or decrease at run time so there is no memory wastage. In
case of array there is lot of memory wastage, like if we declare an array of size 10 and store
only 6 elements in it then space of 4 elements are wasted. There is no such problem in
linked list as memory is allocated only when required.
Implementation
Data structures such as stack and queues can be easily implemented using linked list.
Linked List Operation Pseudocode:
1. Creation of Linked List:
,we will assume that the linked list has three nodes 1 --->2 --->3 with node structure as below:
struct node
{
int data;
struct node *next;
};
Displaying the contents of a linked list is very simple. We keep moving the temp node to the next
one and display its contents.
3. Insert Elements to a Linked List
When temp is NULL, we know that we have reached the end of the linke d lis t so we get out of the
You can add elements to either the beginning, middle or end of the linked list.
while loop.
1. Insert at the beginning
struct node *temp = head;
printf("\n\nList elements are - \n");
Allocate memory for new node
while(temp != NULL)
{
printf("%d
Store data
--->",temp->data);
temp = temp->next;
} Change next of new node to point to head
2.
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = head;
head = newNode;
struct
node *newNode;
Change next pointers to include new node in between
temp->next = newNode;
You can delete either from the beginning, end or from a particular position.
2.
head = head->next;
temp->next = temp->next->next;
Conclusion:
Hence, we studied, how to maintain club member ‘s information using singly linked list
and various operation of singly liked list.
A P J Total
Dated Sign
3 4 3 10
The ticket booking system of Cinemax theater has to be implemented using C++
program. There are 10 rows and 7 seats in each row. Doubly circular linked list has to
be maintained to keep track of free seats at rows. Assume some random booking to
start with. Use array to store pointers (Head pointer) to each row. On demand
a) The list of available seats is to be displayed
b) The seats are to be booked
c) The booking can be cancelled.
Pre-requisite:
Objective:
Theory:
Doubly linked list:
• Doubly linked list is a complex type of linked list in which a node contains a pointer to the
previous as well as the next node in the sequence.
• Therefore, in a doubly linked list, a node consists of three parts: node data, pointer to the
next node in sequence (next pointer) , pointer to the previous node (previous pointer). A
sample node in a doubly linked list is shown in the figure.
• In doubly linked list, from every node the list can be traversed in both the directions.
•
A doubly linked list containing three nodes having numbers from 1 to 3 in their data
struct node
{
struct node *prev;
int data;
struct node *next;
}
Memory Representation of a doubly linked list:
Circular doubly linked list is a more complexed type of data structure in which a node contains
pointers to its previous node as well as the next node. Circular doubly linked list doesn't contain
NULL in any of the node. The last node of the list contains the address of the first node of the
list. The first node of the list also contains address of the last node in its previous pointer.
The following figure shows the way in which the memory is allocated for a circular doubly linked
list. The variable head contains the address of the first element of the list i.e. 1 hence the starting
node of the list contains data A is stored at address 1. Since, each node of the list is supposed to
have three parts therefore, the starting node of the list contains address of the last node i.e. 8 and
the next node i.e. 4. The last node of the list that is stored at address 8 and containing data as 6,
contains address of the first node of the list as shown in the image i.e. 1. In circular doubly linked
list, the last node is identified by the address of the first node which is stored in the next part of the
last node therefore the node which contains the address of the first node, is actually the last node of
the list.
There are various operations which can be performed on circular doubly linked list. The node
structure of a circular doubly linked list is similar to doubly linked list. However, the operations on
circular doubly linked list is described in the following table.
SN Operation Description
2 Insertion at end Adding a node in circular doubly linked list at the end.
4 Deletion at end Removing a node in circular doubly linked list at the end.
Traversing and searching in circular doubly linked list is similar to that in the circular singly linked
list.
Implementation:
This program is a implementation of Ticket Booking System using Doubly Circular Linked List.
Data structures used in the program- Doubly Circular Linked List.
FUNCTIONS USED : -
1] create() :- To create 70 nodes internally ( in memory ), each node represent one seat.
3] book_seat() :- it will take input from user as seat no. If booking status of that seat is ‘a’
then avaibility status of that seat will change from (a) to (b) . else it will show an error message.
If Seat is booked succesfully the it will display pin for each seat.
4] cancle_seat() :- the purpose of assigning pin to each seat is only one who has booked the seat
can cancel it. So at the time of cancelation pins are required .
Now at cancelation time it wil ask for seat number and pin if seat number and pin combination
matches and the avaibility status of that seat is booked then that seat will be cancled. Else it will
give an error message.
Conclusion:
Hence, we studied how to we can book or cancel movie ticket using doubly Circular linked
lists.
A P J Total
Dated Sign
3 4 3 10
Write C++ program for storing appointment schedule for day. Appointments are
booked randomly using linked list. Set start and end time and min and
max duration for visit slot.Write functions for
a) Display free slots
b) Book appointment
c) Cancel appointment ( check validity, time bounds, availability etc)
d) Sort list based on time
e) Sort list based on time using pointer
Pre-requisite:
Objective:
• To book or cancel appointment using linked list.
Theory:
Linked List:
A linked list is a linear data structure, in which the elements are not stored at contiguous memory
locations. The elements in a linked list are linked using pointers as shown in the below image:
In simple words, a linked list consists of nodes where each node contains a data field and a
reference(link) to the next node in the list.
#include<iostream>
#include<string.h>
using namespace std;
int nodes;
struct appoint
{
int status;
char start[10];
char end[10];
char max[10];
char min[10];
struct appoint *Next;
}*head;
void create_app()
{
int i ;
appoint *temp, *p;
head = NU LL;
cfooru(ti<
=<0;"\in<\noH
deosw; im
++an) y Appointments";
{in>>nodes;
c
cout<<" NEW APPOINTMENT ";
temp = new(struct appoint); //Step 1: Allocate Memory
temp->status=0;
cout<<"\n\t Enter Start Time: "; //Step 2: Store data and address
cin>>temp->start;
cout<<"\n\t Enter End Time: "; //Step 2: Store data and address
cin>>temp->end;
cout<<"\n\t Enter min Time: "; //Step 2: Store data and address
cin>>temp->min;
cout<<"\n\t Enter max Time: "; //Step 2: Store data and address
cin>>temp->max;
temp->Next = NULL;
}
}
void display_SLL()
{
appoint *p;
}
void book_app()
{
char time[10];
struct appoint *p;
cout<<"\n\n\tEnter The Time Slot";
cin>>time;
p=head;
while(p!=NULL)
{
if(strcmp(time,p->start) == 0)
{
if(p->status == 0)
{
p->status=1;
cout<<"Your Appointment Is Booked\n\n";
}
else
cout<<"Appointment slot is Busy\n\n";
break;
}
else
p=p->Next;
}
if(p==NULL)
cout<<"\n\n Appointment slot is Not available\n\n";
display_SLL();
void cancel_app()
{
char time[10];
struct appoint *p;
cout<<"\n\n\tEnter Cancellation Time";
cin>>time;
p=head;
while(p!=NULL)
{
if(strcmp(time,p->start) == 0)
{
if(p->status == 1)
{
p->status=0;
cout<<"Your Appointment Is Cancelled\n\n";
}
else
cout<<"Appointment slot is Busy\n\n";
break;
}
else
p=p->Next;
}
if(p==NULL)
cout<<"\n\n Appointment slot is Not available\n\n";
display_SLL();
void sort_app()
{
char str[10];
struct appoint *p;
int i;
for(i=0;i<nodes-1;i++)
{
p = head;
while(p->Next!=NULL)
{
if(strcmp(p->start,p->Next->start)>0)
{
int tmp=p->status;
p->status=p->Next->status;
p->Next->status=tmp;
strcpy(str,p->start);
strcpy(p->start,p->Next->start);
strcpy(p->Next->start,str);
strcpy(str,p->end);
strcpy(p->end,p->Next->end);
strcpy(p->Next->end,str);
strcpy(str,p->min);
strcpy(p->min,p->Next->min);
strcpy(p->Next->min,str);
strcpy(str,p->max);
strcpy(p->max,p->Next->max);
strcpy(p->Next->max,str);
}
p=p->Next;
}
}
cout<<"\n\nSORTED\n";
display_SLL();
}
int main()
{
create_app();
display_SLL();
book_app();
cancel_app();
sort_app();
return 0;
}
Conclusion:
Hence, we studied how to implement linked list to book or cancel appointment.
A P J Total
Dated Sign
3 4 3 10
GROUP - D
Practical No:11(D)
Practical Title: Write C++ program to check well formedness of parenthesis using stack.
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.
Pre-requisite:
• Basics of stack.
• Different operations that can be performed on stack
Objective:
• To check whether the given expression is well parenthesized or not.
Input:
Expression using {},(),[].
Outcome:
• Result of checking well formedness of parenthesis.
Theory:
Definition:
“Stack is data structure in ehich addition and removal of an element is allowed at the same end is
called as top of stack.”
- Stack is also called as Last In First Out(LIFO) list.
Stack is an abstract data type which is defined by the following structure and operation.
Stack operation :
1. createstack( )
2. Push( )
3. Pop( )
4. Peek( )
5. IsEmpty( )
6. IsFull( )
7. Size( )
Stack is a linear data structure which follows a particular order in which the operations are
performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Mainly the following three basic operations are performed in the stack:
Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow
condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in
which they are pushed. If the stack is empty, then it is said to be an Underflow
condition.
Peek or Top: Returns top element of stack.
isEmpty: Returns true if stack is empty, else false.
isfull()
Algorithm of isfull() function −
begin procedure isfull
end procedure
isempty()
Algorithm of isempty() function −
begin procedure isempty
end procedure
Algorithm for PUSH Operation
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
Algorithm for Pop Operation
A simple algorithm for Pop operation can be derived as follows −
data ← stack[top]
top ← top - 1
return data
end procedure
and the last element of string is on the top of stack. After Performing the pop
operations on stack we get string in reverse order .
Implementation:
There are two ways to implement a stack:
Using array
Using linked list
Algorithms :
Functions Used:
1. void push(char ch);
2. char pop();
3. bool isEmpty();
4. bool isFull();
5. void display();
6. void checkParenthesis();
Implementation:
#include<iostream>
using namespace std;
const int MAX=20;
class Stack
{
char str[MAX];
int top;
public:
Stack()
{
top=-1;
}
bool Stack::isFull()
{
if(top==MAX-1)
return 1;
else
return 0;
}
char Stack::pop()
{
if(!isEmpty())
{
char ch=str[top];
top--;
return ch;
}
else
{
return '\0';
}
}
void Stack::checkParenthesis()
{
cout<<"\nEnter # as a deliminator after expression(At the end)\n";
cout<<"\nEnter Expression: ";
cin.getline(str,MAX,'#');
char ch;
bool flag=0;
Parvatibai Genba Moze College of Engineering Wagholi, Pune
FD
Structure Structure
for(int i=0;str[i]!='\0';i++)
{
if(str[i]=='(' || str[i]=='[' || str[i]=='{')
push(str[i]);
if(str[i]==')'||str[i]==']'||str[i]=='}')
{
ch=pop();
if((str[i]==')'&& ch!='(') ||(str[i]==']'&&
ch!='[')||(str[i]=='}'&& ch!='{'))
{
cout<<"\nNot parenthesized At "<<i<<" =
"<<str[i];
flag=1;
break;
}
}
}
int main()
{
int choice;
do
{
Stack s;
s.checkParenthesis();
cout<<"\nDO you want to continue?{1/0)";
cin>>choice;
}while(choice!=0);
return 0;
}
Conclusion:
Hence, we studied implementation of stack operation.
A P J Total
Dated Sign
3 4 3 10
Practical No:12(D)
Practical Title: Write a C++ program for expression conversion as infix to
postfix and its evaluation using stack
Aim: Implement C++ program for expression conversion as infix to postfix and its
evaluation using stack based on given conditions
i. Operands and operator, both must be single character.
ii. Input Postfix expression must be in a desired format.
iii. Only '+', '-', '*' and '/ ' operators are expected
Pre-requisite:
• Basics of stack.
• Different operations that can be performed on stack
Input:
Infix expression
Theory :
A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is
named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of plates,
etc.
A real-world stack allows operations at one end only. For example, we can place or remove a card
or plate from the top of the stack only. Likewise, 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. Here, the element which
is placed (inserted or added) last, is accessed first. In stack terminology, insertion operation is called
PUSH operation and removal operation is called POP operation.
Stack Representation
The following diagram depicts a stack and its operations −
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 a sense of dynamic resizing. Here, we are going to implement
stack using arrays, which makes it a fixed size stack implementation.
Basic Operations
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.
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.
APPLICATION OF STACKs
Convert infix expression to postfix and prefix expressions
Evaluate the postfix expression
Reverse a string
Check well-formed (nested) parenthesis
Reverse a string
Process subprogram function calls
Parse (analyze the structure) of computer programs
Simulate recursion
Polish Notation:
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
2 (a + b) ∗ c ∗+ab ab+c∗
c
3 a ∗ (b + c) ∗a+b abc+∗
c
4 a/b+c/d +/ab/cd ab/cd/+
5 (a + b) ∗ (c + d) ∗+ab+cd ab+cd+∗
Following is the algorithm to convert infix expression into Reverse Polish notation.
Example:
Implementation:
1. #include<iostream>
2. #include<stack>
3. using namespace std;
4. // defines the Boolean function for operator, operand, equalOrhigher precedence and the stri
ng conversion function.
5. bool IsOperator(char);
6. bool IsOperand(char);
7. bool eqlOrhigher(char, char);
8. string convert(string);
9.
10. int main()
11. {
12. string infix_expression, postfix_expression;
13. int ch;
14. do
15. {
16. cout << " Enter an infix expression: ";
17. cin >> infix_expression;
18. postfix_expression = convert(infix_expression);
19. cout << "\n Your Infix expression is: " << infix_expression;
20. cout << "\n Postfix expression is: " << postfix_expression;
21. cout << "\n \t Do you want to enter infix expression (1/ 0)?";
22. cin >> ch;
23. //cin.ignore();
24. } while(ch == 1);
25. return 0;
26. }
27.
28. // define the IsOperator() function to validate whether any symbol is operator.
29. /* If the symbol is operator, it returns true, otherwise false. */
30. bool IsOperator(char c)
31. {
32. if(c == '+' || c == '-' || c == '*' || c == '/' || c == '^' )
33. return true;
34. return false;
35. }
36.
37. // IsOperand() function is used to validate whether the character is operand.
38. bool IsOperand(char c)
39. {
40. if( c >= 'A' && c <= 'Z') /* Define the character in between A to Z. If not, it returns False.*
/
41. return true;
42. if (c >= 'a' && c <= 'z') // Define the character in between a to z. If not, it returns False. */
43. return true;
44. if(c >= '0' && c <= '9') // Define the character in between 0 to 9. If not, it returns False. */
45. return true;
46. return false;
47. }
48. // here, precedence() function is used to define the precedence to the operator.
49. int precedence(char op)
50. {
51. if(op == '+' || op == '-') /* it defines the lowest precedence */
52. return 1;
53. if (op == '*' || op == '/')
54. return 2;
55. if(op == '^') /* exponent operator has the highest precedence *
56. return 3;
57. return 0;
58. }
59. /* The eqlOrhigher() function is used to check the higher or equal precedence of the two op
erators in infix expression. */
60. bool eqlOrhigher (char op1, char op2)
61. {
62. int p1 = precedence(op1);
63. int p2 = precedence(op2);
64. if (p1 == p2)
65. {
66. if (op1 == '^' )
67. return false;
68. return true;
69. }
70. return (p1>p2 ? true : false);
71. }
72.
73. /* string convert() function is used to convert the infix expression to the postfix expression
of the Stack */
74. string convert(string infix)
75. {
76. stack <char> S;
77. string postfix ="";
78. char ch;
79.79.
80. S.push( '(' );
81. infix += ')';
82.
83. for(int i = 0; i<infix.length(); i++)
84. {
85. ch = infix[i];
86.
87. if(ch == ' ')
88. continue;
89. else if(ch == '(')
90. S.push(ch);
91. else if(IsOperand(ch))
Conclusion:
By this way, we can perform expression conversion as infix to postfix and its evaluation
using stack
A P J Total
Dated Sign
3 4 3 10
Question Bank:
1. What is Stack?
2. Which are the different operations that can be performed on stack?
3. Explain PUSH, POP operations on stack
4. What are the applications of stack?
5. What is infix, postfix and prefix expression?
6. Conversion – infix to postfix, infix to prefix , etc.
7. Evaluation of infix, postfix and prefix expression
GROUP - E
Pre-requisite:
• Basics of Queue
• Different operations that can be performed on queue
Objective:
• To perform addition and deletion operations on queue.
Theory :
Queue:
A Queue is a linear structure which follows a particular order in which the operations are performed.
The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a
resource where the consumer that came first is served first. The difference between stacks and queues
is in removing. In a stack we remove the item the most recently added; in a queue, we remove the
item the least recently added.
Basic Operations
Queue operations may involve initializing or defining the queue, utilizing it, and then completely
erasing it from the memory. Here we shall try to understand the 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 the above-mentioned queue operation efficient. These are
−
peek() − Gets the element at the front of the queue without removing it.
isfull() − Checks if the queue is full.
isempty() − Checks if the queue is empty.
In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing (or
storing) data in the queue we take help of rear pointer.
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 the queue is full. In case we maintain the queue in a circular
linked-list, the algorithm will differ. Algorithm of isfull() function −
Algorithm
end procedure
isempty()
Algorithm of isempty() function −
Algorithm
endif
end procedure
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
Applications of Queue:
Queue is used when things don’t have to be processed immediatly, but have to be processed
in First InFirst Out order like Breadth First Search. This property of Queue makes it also useful
in following kind of scenarios.
1) When a resource is shared among multiple consumers. Examples include CPU scheduling,
Disk Scheduling.
2) When data is transferred asynchronously (data not necessarily received at same rate as sent)
between two processes. Examples include IO Buffers, pipes, file IO, etc..
Implementation:
#include <iostream>
#define MAX 10
using namespace std;
struct queue
{ int data[MAX];
int front,rear;
};
class Queue
{ struct queue q;
public:
Queue(){q.front=q.rear=-1;}
int isempty();
int isfull();
void enqueue(int);
int delqueue();
void display();
};
int Queue::isempty()
{
return(q.front==q.rear)?1:0;
}
int Queue::isfull()
{ return(q.rear==MAX-1)?1:0;}
void Queue::enqueue(int x)
{q.data[++q.rear]=x;}
int Queue::delqueue()
{return q.data[++q.front];}
void Queue::display()
{ int i;
cout<<"\n";
for(i=q.front+1;i<=q.rear;i++)
cout<<q.data[i]<<" ";
}
int main()
{ Queue obj;
int ch,x;
do{ cout<<"\n 1. insert job\n 2.delete job\n 3.display\n 4.Exit\n Enter your choice:";
cin>>ch;
switch(ch)
{ case 1: if (!obj.isfull())
{ cout<<"\n Enter data:";
cin>>x;
obj.enqueue(x);
}
else
cout<< "Queue is overflow";
break;
case 2: if(!obj.isempty())
cout<<"\n Deleted Element="<<obj.delqueue();
else
{ cout<<"\n Queue is underflow"; }
cout<<"\nremaining jobs :";
obj.display();
break;
case 3: if (!obj.isempty())
{ cout<<"\n Queue contains:";
obj.display();
}
else cout<<"\n Queue is empty";
break;
Conclusion:
By this way, we can perform different operations on queue
A P J Total
Dated Sign
3 4 3 10
Question Bank:
1. What is Queue?
2. What are the different operations that can be performed on queue?
3. Explain all the operations on queue
4. Which are different types of queues , Explain.
Pre-requisite:
• Knowledge of Queue
• Types of queue
• Knowledge of double ended queue and different operations that can be performed
on it
Objective: • To simulate deque with functions to add and delete elements from either end of the
deque.
Outcome: • Result of deque with functions to add and delete elements from either end of the
deque.
Theory :
The dequeue stands for Double Ended Queue. In the queue, the insertion takes place from one end
while the deletion takes place from another end. The end at which the insertion occurs is known as
the rear end whereas the end at which the deletion occurs is known as front end.
Deque is a linear data structure in which the insertion and deletion operations are performed from
both ends. We can say that deque is a generalized version of the queue.
There are two types of Queues, Input-restricted queue, and output-restricted queue.
1. Input-restricted queue: The input-restricted queue means that some restrictions are
applied to the insertion. In input-restricted queue, the insertion is applied to one end while
2. Output-restricted queue: The output-restricted queue means that some restrictions are
applied to the deletion operation. In an output-restricted queue, the deletion can be applied
only from one end, whereas the insertion is possible from both ends.
Operations on Deque
o Insert at front
o Delete from end
o insert at rear
o delete from rear
Other than insertion and deletion, we can also perform peek operation in deque.
Through peek operation, we can get the front and the rear element of the dequeue.
o isFull(): This function returns a true value if the stack is full; otherwise, it returns a false
value.
o isEmpty(): This function returns a true value if the stack is empty; otherwise it returns a
false value.
Step -1:
[Check for
overflow]
if(rear==M
AX)
Print("Queu
e is
Overflow”);
return;
Step-2: [Insert element] else rear=rear+1;
q[rear]=no;
[Set rear and front pointer]
if rear=0
rear=1;
if front=0
front=1;
Step-3: return
void add_item_rear()
{
int num;
printf("\n Enter Item to insert : ");
scanf("%d",&num);
if(rear==MAX)
{
printf("\n Queue is Overflow");
return;
}
else
{
rear++;
q[rear]=num;
if(rear==0)
rear=1;
if(front==0)
front=1;
}
}
void add_item_front()
{
int num;
printf("\n Enter item to insert:");
scanf("%d",&num);
FD
Parvatibai Genba Moze College of Engineering Wagholi,
Structure Structure
if(front<=1)
{
printf("\n Cannot add item at front end");
return;
}
else
{
front--;
q[front]=num;
}
}
void delete_item_front()
{
int num;
if(front==0)
{
printf("\n Queue is Underflow\n");
return;
}
else
{
num=q[front];
printf("\n Deleted item is %d\n",num);
if(front==rear)
{
front=0;
rear=0;
}
else
{
front++;
FD
Parvatibai Genba Moze College of Engineering Wagholi,
Structure Structure
}
}
void delete_item_rear()
{
int num;
if(rear==0)
{
printf("\n Cannot delete item at rear end\n");
return;
}
else
{
num=q[rear];
if(front==rear)
{
front=0;
rear=0;
}
else
{
rear--;
printf("\n Deleted item is %d\n",num);
}
}
}
FD
Parvatibai Genba Moze College of Engineering Wagholi,
Conclusion:
By this way, we can perform operations on double ended queue
A P J Total
Dated Sign
3 4 3 10
Question Bank:
1. What is queue?
2. Types of queue
3. What is double ended queue?
4. How to insert the new node in Doubly Link List?
5. How to delete the node from front of Doubly Link List ?
6. How to delete the node from end of Doubly Link List ?
7. How to delete the node in between of Doubly Link List
96
THANKS..
PROF. Vidya Yenegur
ASSISTANT PROFESSOR
PARVATIBAI GENBA MOZE COLLEGE OF
ENGINEERING WAGHOLI PUNE 412207
97