DSA lab-AIDS
DSA lab-AIDS
) - 637 304
LAB RECORD
REGISTER NUMBER :
\ YEAR/SEM :
COURSE/BRANCH :
RECORD NOTEBOOK
Certified that this is a Bonafide record of Practical work done by Mr. /Ms. ..................................................
Laboratory.
MISSION
• Achieving excellence in Teaching Learning process using state-of-the-art resources
• Extending opportunity to upgrade faculty knowledge and skills.
• Implementing the best student training practices for requirements of industrial scenario of the state
• Motivating faculty and students in research activity for real time application
MISSION
M1: To empower the cognitive skills of the students in the pioneering domain of Artificial
Intelligence and Data Science by providing content based learning with quality teaching and
learning opportunities, industry institute interaction activities and centers of excellence.
M2: To transform professionals into technically competent to contribute to the society positively by
inducing entrepreneurship skills through collaborative teaching, innovations and research.
M3: To Forge partnerships with companies to tackle real-world challenges using AI solutions,
facilitating research projects and internships to bridge academia and industry.
Program Outcomes (POs):
PO1 Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution of complex engineering problems.
PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics, natural
sciences and engineering sciences.
PO3 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, safety, cultural, societal and environmental considerations.
PO4 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.
PO5 Modern tool usage: Create, select, apply appropriate techniques, resources, modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal, cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7 Environment and sustainability: Understand the impact of the professional engineering
solutions in societal, environmental contexts, demonstrate the knowledge and need for sustainable
development.
PO8 Ethics: Apply ethical principles, commit to professional ethics, responsibilities and norms of
the engineering practice.
PO9 Individual and team work: Function effectively as an individual, as a member or leader in
diverse teams and in multidisciplinary settings.
PO11 Project management and finance: Demonstrate knowledge, 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.
PO12 Life-long learning: Recognize the need, ability to engage in independent and life-long
learning in the broadest context of technological change.
PSO2 – To apply software skills in developing algorithms for solving healthcare related problems in
various fields of medical sector.
PSO3 – To adapt to emerging information and communication technologies (ICT) for current societal
and scientific issues thereby developing indigenous medical instruments that are on par with the
existing biomedical technology.
PEO2 – To enable the graduates to exhibit leadership, make decisions with societal and ethical
responsibilities, function and communicate effectively in multidisciplinary settings.
PEO3 – To ensure that graduates will recognize the need for sustaining and expanding their technical
competence and engage in learning opportunities throughout their careers.
LIST OF EXPERIMENT
S. PAGE
DATE EXPERIMENT MARKS SIGNATURE
NO NO.
Write a program that uses functions to perform the following operations on singly linked list i)
Creation ii) Insertion iii) Deletion iv) Traversal
Aim:
To write a Python program to implement singly linked list.
Algorithm:
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variable head.
3. The variable head points to the first element in the singly linked list.
4.Define methods get_node, get_prev_node, insert_after, insert_before, insert_at_beg, insert_at_end,
remove and display.
5. get_node takes an index as argument and traverses the list from the first node that many times to
return the node at that index.
6. get_prev_node takes a reference node as argument and returns the previous node. It returns None
when the reference node is the first node.
7. The methods insert_after and insert_before insert a node after or before some reference node in the
list.
8. The methods insert_at_beg and insert_at_end insert a node at the first or last position of the list.
9. The method remove takes a node as argument and removes it from the list.
10. The method display traverses the list from the first node and prints the data of each node.
11. Create an instance of LinkedList and present the user with a menu to perform operations on the list.
Program:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def get_node(self, index):
current = self.head
for i in range(index):
if current is None:
return None
current = current.next
return current
def get_prev_node(self, ref_node):
current = self.head
while (current and current.next != ref_node):
current = current.next
return current
def insert_after(self, ref_node, new_node):
new_node.next = ref_node.next
ref_node.next = new_node
def insert_before(self, ref_node, new_node):
prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)
def insert_at_beg(self, new_node):
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def insert_at_end(self, new_node):
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
def remove(self, node):
prev_node = self.get_prev_node(node)
if prev_node is None:
self.head = self.head.next
else:
prev_node.next = node.next
def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next
a_llist = LinkedList()
print('Menu')
print('insert <data> after <index>')
print('insert <data> before <index>')
print('insert <data> at beg')
print('insert <data> at end')
print('remove <index>')
print('quit')
while True:
print('The list: ', end = '')
a_llist.display()
print()
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_llist.insert_at_beg(new_node)
elif position == 'end':
a_llist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_llist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_llist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_llist.insert_before(ref_node, new_node)
elif operation == 'remove':
index = int(do[1])
node = a_llist.get_node(index)
if node is None:
print('No such index.')
continue
a_llist.remove(node)
elif operation == 'quit':
break
Output:
Case 1:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 7 at beg
The list: 7
What would you like to do? insert 3 at end
The list: 7 3
What would you like to do? insert 1 after 0
The list: 7 1 3
What would you like to do? insert 9 before 2
The list: 7 1 9 3
What would you like to do? remove 2
The list: 7 1 3
What would you like to do? insert 12 at end
The list: 7 1 3 12
What would you like to do? remove 0
The list: 1 3 12
What would you like to do? quit
Case 2:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 5 after 0
No such index.
The list:
What would you like to do? insert 3 at end
The list: 3
What would you like to do? insert 1 after 0
The list: 3 1
What would you like to do? insert 2 before 1
The list: 3 2 1
What would you like to do? insert 0 at end
The list: 3 2 1 0
What would you like to do? remove 3
The list: 3 2 1
What would you like to do? remove 2
The list: 3 2
What would you like to do? Quit
Result:
Thus, the Singly linked list program of varies operation was executed and verified
Ex. No:2
Date:
Write a program that uses functions to perform the following operations on doubly linked list i)
Creation ii) Insertion iii) Deletion iv) Traversal.
Aim:
To write a Python program to implement doubly linked list.
Algorithm:
1. Create a class Node with instance variables data and next.
2. Create a class DoublyLinkedList with instance variables first and last.
3. The variable first points to the first element in the doubly linked list while last points to the last
element.
4. Define methods get_node, insert_after, insert_before, insert_at_beg, insert_at_end, remove and
display.
5. get_node takes an index as argument and traverses the list from the first node that many times to
return the node at that index.
6. The methods insert_after and insert_before insert a node after or before some reference node in the
list.
7. The methods insert_at_beg and insert_at_end insert a node at the first or last position of the list.
8. The method remove takes a node as argument and removes it from the list.
9. The method display traverses the list from the first node and prints the data of each node.
10. Create an instance of DoublyLinkedList and present the user with a menu to perform operations on
the list.
Program:
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.first = None
self.last = None
def get_node(self, index):
current = self.first
for i in range(index):
if current is None:
return None
current = current.next
return current
def insert_after(self, ref_node, new_node):
new_node.prev = ref_node
if ref_node.next is None:
self.last = new_node
else:
new_node.next = ref_node.next
new_node.next.prev = new_node
ref_node.next = new_node
def insert_before(self, ref_node, new_node):
new_node.next = ref_node
if ref_node.prev is None:
self.first = new_node
else:
new_node.prev = ref_node.prev
new_node.prev.next = new_node
ref_node.prev = new_node
def insert_at_beg(self, new_node):
if self.first is None:
self.first = new_node
self.last = new_node
else:
self.insert_before(self.first, new_node)
def insert_at_end(self, new_node):
if self.last is None:
self.last = new_node
self.first = new_node
else:
self.insert_after(self.last, new_node)
def remove(self, node):
if node.prev is None:
self.first = node.next
else:
node.prev.next = node.next
if node.next is None:
self.last = node.prev
else:
node.next.prev = node.prev
def display(self):
current = self.first
while current:
print(current.data, end = ' ')
current = current.next
a_dllist = DoublyLinkedList()
print('Menu')
print('insert <data> after <index>')
print('insert <data> before <index>')
print('insert <data> at beg')
print('insert <data> at end')
print('remove <index>')
print('quit')
while True:
print('The list: ', end = '')
a_dllist.display()
print()
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_dllist.insert_at_beg(new_node)
elif position == 'end':
a_dllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_dllist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_dllist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_dllist.insert_before(ref_node, new_node)
elif operation == 'remove':
index = int(do[1])
node = a_dllist.get_node(index)
if node is None:
print('No such index.')
continue
a_dllist.remove(node)
elif operation == 'quit':
break
Output:
Case 1:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 5 at beg
The list: 5
What would you like to do? insert 3 at beg
The list: 3 5
What would you like to do? insert 1 at end
The list: 3 5 1
What would you like to do? insert 10 after 1
The list: 3 5 10 1
What would you like to do? insert 0 before 2
The list: 3 5 0 10 1
What would you like to do? remove 4
The list: 3 5 0 10
What would you like to do? remove 1
The list: 3 0 10
What would you like to do? remove 5
No such index.
The list: 3 0 10
What would you like to do? quit
Case 2:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 3 after 0
No such index.
The list:
What would you like to do? insert 2 at beg
The list: 2
What would you like to do? insert 3 before 0
The list: 3 2
What would you like to do? remove 0
The list: 2
What would you like to do? remove 0
The list:
What would you like to do? Quit
Result:
Thus, the doubly linked list program of varies operation was executed and verified
Ex. No:3
Date:
Write a program that uses functions to perform the following operations on circular
linked List i) Creation ii) Insertion iii) Deletion iv) Traversal.
Aim:
Write a Python program to implement circular linked list.
Algorithm:
1. Create a class Node with instance variables data and next.
2. Create a class CircularLinkedList with instance variable head.
3. The variable head points to the first element in the circular single linked list.
4. Define methods get_node, get_prev_node, insert_after, insert_before, insert_at_beg, insert_at_end,
remove and display.
5. get_node takes an index as argument and traverses the list from the first node that many times to
return the node at that index. It stops if it reaches the first node again.
6. get_prev_node takes a reference node as argument and returns the previous node.
7. The methods insert_after and insert_before insert a node after or before some reference node in the
list.
8. The methods insert_at_beg and insert_at_end insert a node at the first or last position of the list.
9. The method remove takes a node as argument and removes it from the list.
10. The method display traverses the list from the first node and prints the data of each node. It stops
when it reaches the first node again.
11. Create an instance of CircularLinkedList and present the user with a menu to perform operations on
the list.
Program:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def get_node(self, index):
if self.head is None:
return None
current = self.head
for i in range(index):
current = current.next
if current == self.head:
return None
return current
def get_prev_node(self, ref_node):
if self.head is None:
return None
current = self.head
while current.next != ref_node:
current = current.next
return current
def insert_after(self, ref_node, new_node):
new_node.next = ref_node.next
ref_node.next = new_node
def insert_before(self, ref_node, new_node):
prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)
def insert_at_end(self, new_node):
if self.head is None:
self.head = new_node
new_node.next = new_node
else:
self.insert_before(self.head, new_node)
def insert_at_beg(self, new_node):
self.insert_at_end(new_node)
self.head = new_node
def remove(self, node):
if self.head.next == self.head:
self.head = None
else:
prev_node = self.get_prev_node(node)
prev_node.next = node.next
if self.head == node:
self.head = node.next
def display(self):
if self.head is None:
return
current = self.head
while True:
print(current.data, end = ' ')
current = current.next
if current == self.head:
break
a_cllist = CircularLinkedList()
print('Menu')
print('insert <data> after <index>')
print('insert <data> before <index>')
print('insert <data> at beg')
print('insert <data> at end')
print('remove <index>')
print('quit')
while True:
print('The list: ', end = '')
a_cllist.display()
print()
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_cllist.insert_at_beg(new_node)
elif position == 'end':
a_cllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_cllist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_cllist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_cllist.insert_before(ref_node, new_node)
elif operation == 'remove':
index = int(do[1])
node = a_cllist.get_node(index)
if node is None:
print('No such index.')
continue
a_cllist.remove(node)
elif operation == 'quit':
break Output:
Case 1:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 7 at beg
The list: 7
What would you like to do? insert 1 before 0
The list: 7 1
What would you like to do? insert 10 after 0
The list: 7 10 1
What would you like to do? insert 3 at end
The list: 7 10 1 3
What would you like to do? remove 2
The list: 7 10 3
What would you like to do? remove 0
The list: 10 3
What would you like to do? quit
Case 2:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 1 at beg
The list: 1
What would you like to do? insert 3 after 2
No such index.
The list: 1
What would you like to do? remove 1
No such index.
The list: 1
What would you like to do? insert 6 after 0
The list: 1 6
What would you like to do? remove 0
The list: 6
What would you like to do? quit
Result:
Thus, the circularly linked list program of varies operation was executed and verified
Ex. No:4
Date:
Write a program that implements stack (its operations) using Linked list (Pointers).
Aim:
To write a Python program to implement stack using Linked list.
Algorithm:
1. Create a class Node with instance variables data and next.
2. Create a class Stack with instance variable head.
3. The variable head points to the first element in the linked list.
4. Define methods push and pop inside the class Stack.
5. The method push adds a node at the front of the linked list.
6. The method pop returns the data of the node at the front of the linked list and removes the node.
7. It returns None if there are no nodes.
8. Create an instance of Stack and present a menu to the user to perform operations on the stack.
Program:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push(self, data):
if self.head is None:
self.head = Node(data)
else:
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def pop(self):
if self.head is None:
return None
else:
popped = self.head.data
self.head = self.head.next
return popped
a_stack = Stack()
while True:
print('push <value>')
print('pop')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'push':
a_stack.push(int(do[1]))
elif operation == 'pop':
popped = a_stack.pop()
if popped is None:
print('Stack is empty.')
else:
print('Popped value: ', int(popped))
elif operation == 'quit':
break
Output:
Case 1:
push <value>
pop
quit
What would you like to do? push 15
push <value>
pop
quit
What would you like to do? push 3
push <value>
pop
quit
What would you like to do? pop
Popped value: 3
push <value>
pop
quit
What would you like to do? pop
Popped value: 15
push <value>
pop
quit
What would you like to do? pop
Stack is empty.
push <value>
pop
quit
What would you like to do? quit
Case 2:
push <value>
pop
quit
What would you like to do? pop
Stack is empty.
push <value>
pop
quit
What would you like to do? Quit
Result:
Thus, the stack of linked list operation was executed and verified
Ex. No:5
Date:
Write a program that implements Queue (its operations) using Linked list (Pointers).
Aim:
To write a Python program to implement Queue using linked list.
Algorithm:
1. Create a class Node with instance variables data and next.
2. Create a class Queue with instance variables head and last.
3. The variable head points to the first element in the linked list while last points to the last element.
4. Define methods enqueue and dequeue inside the class Queue.
5. The method enqueue adds a node at the end of the linked list.
6. The method dequeue returns the data of the node at the front of the linked list and removes the node.
It returns None if there are no nodes.
7. Create an instance of Queue and present a menu to the user to perform operations on the queue.
Program:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.head = None
self.last = None
def enqueue(self, data):
if self.last is None:
self.head = Node(data)
self.last = self.head
else:
self.last.next = Node(data)
self.last = self.last.next
def dequeue(self):
if self.head is None:
return None
else:
to_return = self.head.data
self.head = self.head.next
return to_return
a_queue = Queue()
while True:
print('enqueue <value>')
print('dequeue')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'enqueue':
a_queue.enqueue(int(do[1]))
elif operation == 'dequeue':
dequeued = a_queue.dequeue()
if dequeued is None:
print('Queue is empty.')
else:
print('Dequeued element: ', int(dequeued))
elif operation == 'quit':
break
Output:
Case 1:
enqueue <value>
dequeue
quit
What would you like to do? enqueue 3
enqueue <value>
dequeue
quit
What would you like to do? enqueue 4
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued element: 3
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued element: 4
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Queue is empty.
enqueue <value>
dequeue
quit
What would you like to do? Quit
Result:
Thus, the queue of linked list operation was executed and verified
Ex. No:6A
Date:
Write a program that uses both recursive and non-recursive functions to perform the
following searching operations for a Key value in a given list of integers: a) Linear search
Aim:
To write a Python program to implement linear search using non-recursive function.
Program:
def linear_search(alist, key):
"""Return index of key in alist. Return -1 if key not present."""
for i in range(len(alist)):
if alist[i] == key:
return i
return -1
alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))
index = linear_search(alist, key)
if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))
Output:
Enter the list of numbers: 5 4 3 2 1 10 11 2
The number to search for: 1
1 was found at index 4.
Result:
Thus, the linear search program was executed and verified
Ex. No:6B
Date:
Write a program that uses both recursive and non-recursive functions to perform the
following searching operations for a Key value in a given list of integers: a) Binary search
Aim:
To write a Python program to implement binary search using recursion.
Algorithm:
1. Create a function binary_search that takes a list and the variables start, end and key as arguments.
The function searches for the key in the range [start… end – 1].
2. The base case consists of testing whether start is less than end. If not, -1 is returned.
3. mid is calculated as the floor of the average of start and end.
4. If the element at index mid is less than key, binary_search is called again wit start=mid + 1 and if it is
more than key, it is called with end=mid. Otherwise, mid is returned as the index of the found element.
Program:
def binary_search(alist, start, end, key):
"""Search key in alist[start... end - 1]."""
if not start < end:
return -1
mid = (start + end)//2
if alist[mid] < key:
return binary_search(alist, mid + 1, end, key)
elif alist[mid] > key:
return binary_search(alist, start, mid, key)
else:
return mid
alist = input('Enter the sorted list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))
index = binary_search(alist, 0, len(alist), key)
if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))
Output:
Case 1:
Enter the sorted list of numbers: 4 5 6 7 8 9 10
The number to search for: 9
9 was found at index 5.
Case 2:
Enter the sorted list of numbers: 3 4 5 10
The number to search for: 8
8 was not found.
Result:
Thus, the binary search program was executed and verified
Ex. No:7A
Date:
Write a program that implements the following sorting i) Bubble sort
Aim:
To write a Python program to implement bubble sort.
Algorithm:
1. Define the bubble_sort function that takes a list (alist) as input.
2. Iterate through the list in reverse order, starting from the last index (len(alist) – 1) and ending at the
second index (0) using a step size of -1.
3. Set a flag no_swap to True, indicating no swaps have occurred yet.
4. Enter a nested loop that iterates from the first index (0) to the current outer loop index (i).
5. Compare adjacent elements and swap them if the element on the right is smaller than the element on
the left.
6. Set the no_swap flag to False if a swap occurs, indicating that the list is not yet fully sorted.
7. Check if the no_swap flag is still True after the inner loop completes. If it is, return from the function
as the list is already sorted.
8. Outside the function, prompt the user to enter a list of numbers, which are stored as a string and split
into individual elements.
9. Convert the elements from strings to integers using a list comprehension. 10. Call the bubble_sort
function to sort the list using the Bubble Sort algorithm.
11. Print the sorted list.
Program:
def bubble_sort(alist):
for i in range(len(alist) - 1, 0, -1):
no_swap = True
for j in range(0, i):
if alist[j + 1] < alist[j]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
no_swap = False
if no_swap:
return
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
bubble_sort(alist)
print('Sorted list: ', end='')
print(alist)
Output:
Enter the list of numbers: 58 27 14 67 11
Sorted list: [11, 14, 27, 58, 67]
Result:
Thus, the bubble sort program was executed and verified
Ex. No:7B
Date:
Write a program that implements the following sorting ii) Selection sort
Aim:
To write a Python program to implement selection sort.
Algorithm:
1. Create a function selection_sort that takes a list as argument.
2. Inside the function create a loop with a loop variable i that counts from 0 to the length of the list – 1.
3. Create a variable smallest with initial value i.
4. Create an inner loop with a loop variable j that counts from i + 1 up to the length of the list – 1.
5. Inside the inner loop, if the elements at index j is smaller than the element at index smallest, then set
smallest equal to j.
6. After the inner loop finishes, swap the elements at indexes i and smallest.
7. The sorted list is displayed.
Program:
def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)
Output:
Enter the list of numbers: 58 27 14 67 11
Sorted list: [11, 14, 27, 58, 67]
Result:
Thus, the selection sort program was executed and verified
Ex. No:7C
Date:
Write a program that implements the following sorting iii) Quick sort.
Aim:
To write a Python program to implement quick sort.
Algorithm:
1. The program defines a “quicksort” function that takes a list, start index, and end index as arguments.
2. If the sublist has more than one element, it calls the “partition” function to find the pivot index.
3. Recursively calls “quicksort” to sort the left and right sublists.
4. The “partition” function selects a pivot and rearranges elements to its left and right based on their
values.
5. The program prompts the user to enter a list of numbers and converts them into integers.
6. It calls the “quicksort” function to sort the list.
7. The sorted list is displayed.
Program:
def quicksort(alist, start, end):
'''Sorts the list from indexes start to end - 1 inclusive.'''
if end - start > 1:
p = partition(alist, start, end)
quicksort(alist, start, p)
quicksort(alist, p + 1, end)
def partition(alist, start, end):
pivot = alist[start]
i = start + 1
j = end - 1
while True:
while (i <= j and alist[i] <= pivot):
i=i+1
while (i <= j and alist[j] >= pivot):
j=j-1
if i <= j:
alist[i], alist[j] = alist[j], alist[i]
else:
alist[start], alist[j] = alist[j], alist[start]
return j
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
quicksort(alist, 0, len(alist))
print('Sorted list: ', end='')
print(alist)
Output:
Enter the list of numbers: 85 64 12 57 34 61
Sorted list: [12, 34, 57, 61, 64, 85]
Result:
Thus, the quick sort program was executed and verified
Ex. No:8A
Date:
Write a program that implements the following i) Insertion sort
Aim:
To write a Python program to implement insertion sort.
Algorithm:
1. Define the function insertion_sort that takes a list (alist) as input.
2. Start a loop that iterates from the second element (i = 1) to the end of the list (len(alist)).
3. Assign the value of the current element to a temporary variable (temp).
4. Set the initial index for comparison as the previous element (j = i – 1).
5. Enter a nested loop that continues while the index is greater than or equal to 0 and the temporary
value is less than the element at the current index (temp < alist[j]).
6. Within the nested loop, shift the element at the current index one position to the right (alist[j + 1] =
alist[j]). 7. Decrement the index by 1 (j = j – 1).
8. After exiting the nested loop, insert the temporary value into its correct position in the sorted portion
of the list (alist[j + 1] = temp).
9. Outside the function, prompt the user to enter a list of numbers, which are stored as a string and split
into individual elements.
10. Convert the elements from strings to integers using a list comprehension. 11. Call the insertion_sort
function, passing the converted list as an argument.
12. Print the sorted list.
Program:
def insertion_sort(alist):
for i in range(1, len(alist)):
temp = alist[i]
j=i-1
while (j >= 0 and temp < alist[j]):
alist[j + 1] = alist[j]
j=j-1
alist[j + 1] = temp
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
insertion_sort(alist)
print('Sorted list: ', end='')
print(alist)
Output:
Enter the list of numbers: 85 64 12 57 34 61
Sorted list: [12, 34, 57, 61, 64, 85]
Result:
Thus, the insertion sort program was executed and verified
Ex. No:8B
Date:
Write a program that implements the following ii) Merge sort
Aim:
To write a Python program to implement merge sort.
Algorithm:
1. Create a function merge_sort that takes a list and two variables start and end as arguments.
2. The function merge_sort will sort the list from indexes start to end – 1 inclusive.
3. If end – start is not greater than 1, then return.
4. Otherwise, set mid equal to the floor of (start + end)/2.
5. Call merge_sort with the same list and with start = start and end = mid as arguments.
6. Call merge_sort with the same list and with start = mid and end = end as
arguments. 7. Call the function merge_list, passing the list and the variables start, mid and end as
arguments. 8. The function merge_list takes a list and three numbers, start, mid and end as arguments
and assuming the list is sorted from indexes start to mid – 1 and from mid to end – 1, merges them to
create a new sorted list from indexes start to end – 1.
9. The sorted list is displayed.
Program:
def merge_sort(alist, start, end):
'''Sorts the list from indexes start to end - 1 inclusive.'''
if end - start > 1:
mid = (start + end)//2
merge_sort(alist, start, mid)
merge_sort(alist, mid, end)
merge_list(alist, start, mid, end)
def merge_list(alist, start, mid, end):
left = alist[start:mid]
right = alist[mid:end]
k = start
i=0
j=0
while (start + i < mid and mid + j < end):
if (left[i] <= right[j]):
alist[k] = left[i]
i=i+1
else:
alist[k] = right[j]
j=j+1
k=k+1
if start + i < mid:
while k < end:
alist[k] = left[i]
i=i+1
k=k+1
else:
while k < end:
alist[k] = right[j]
j=j+1
k=k+1
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
merge_sort(alist, 0, len(alist))
print('Sorted list: ', end='')
print(alist)
Output:
Enter the list of numbers: 85 64 12 57 34 61
Sorted list: [12, 34, 57, 61, 64, 85]
Result:
Thus, the merge sort program was executed and verified
Ex. No:8C
Date:
Write a program that implements the following iii) Heap sort.
Aim:
To write a Python program to implement heap sort.
Algorithm:
1. Create a function heapsort that takes a list as argument.
2. Call build_max_heap with the list as argument to rearrange the list into a list representation of a
heap.
3. Swap the first element with the last element in the heap.
4. Consider the new heap to have size one less than its previous size and call max_heapify with index =
0 to make this new heap satisfy the heap property.
5. Repeat steps 3 and 4 until the size of the heap reduces to zero and the entire list is sorted.
6. Define the function parent that takes an index as argument and returns the index of the parent. 7.
Define the function left that takes an index as argument and returns the index of its left child. 8. Define
the function right that takes an index as argument and returns the index of its right child.
9. Define the function build_max_heap that takes a list as argument and rearranges it to form a max
heap.
10. The build_max_heap function works by calling max_heapify on each parent node starting from the
last parent node and working towards the root.
11. Define the function max_heapify that takes an index as argument and modifies the heap structure at
and below the node at this index to make it satisfy the heap property.
12. The user is prompted to enter a list of numbers.
13. The list is passed to the heapsort function.
14. The sorted list is displayed.
Program:
def heapsort(alist):
build_max_heap(alist)
for i in range(len(alist) - 1, 0, -1):
alist[0], alist[i] = alist[i], alist[0]
max_heapify(alist, index=0, size=i)
def parent(i):
return (i - 1)//2
def left(i):
return 2*i + 1
def right(i):
return 2*i + 2
def build_max_heap(alist):
length = len(alist)
start = parent(length - 1)
while start >= 0:
max_heapify(alist, index=start, size=length)
start = start - 1
def max_heapify(alist, index, size):
l = left(index)
r = right(index)
if (l < size and alist[l] > alist[index]):
largest = l
else:
largest = index
if (r < size and alist[r] > alist[largest]):
largest = r
if (largest != index):
alist[largest], alist[index] = alist[index], alist[largest]
max_heapify(alist, largest, size)
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
heapsort(alist)
print('Sorted list: ', end='')
print(alist)
Output:
Enter the list of numbers: 85 64 12 57 34 61
Sorted list: [12, 34, 57, 61, 64, 85]
Result:
Thus, the heap sort program was executed and verified
Ex. No:9
Date:
Write a program to perform the following operations: a) Insert an element into a binary search
tree. b) Delete an element from a binary search tree. c) Search for a key element in a binary
search tree.
Aim:
To write a python program to create, delete and search values in binary search tree.
Algorithm:
1. Create a class BSTNode with instance variables key, left, right and parent.
2. Define methods insert, inorder, replace_node_of_parent, find_min, remove and search in BSTNode.
3. The method insert takes a node as argument and inserts that node in the BST with the BSTNode
object as root.
4. The method inorder displays the inorder traversal of the BST with the
BSTNode object as root.
5. The method replace_node_of_parent takes a node as argument and replaces the current object in the
BST with the node.
6. The method find_min finds the the left-most node in the BST with the BSTNode object as root.
7. The method remove removes the current BSTNode object from the BST.
8. The method search takes a key as argument and returns the node with that key in the BST with the
BSTNode object as root.
9. Create a class BSTree with instance variable root.
10. Define methods inorder, add, remove and search in BSTree.
11. The method inorder calls the inorder method of the root node.
12. The method add takes a key as argument and adds a node with that key by calling the insert method
of the root node.
13. The method search takes a key as argument and returns the node with that key by calling the search
method of the root node.
14. The method remove takes a key as argument and removes the node with that key. If the node is the
root node then the instance variable root is set to None otherwise the remove method of the node is
called.
Program:
class BSTNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.parent = None
def insert(self, node):
if self.key > node.key:
if self.left is None:
self.left = node
node.parent = self
else:
self.left.insert(node)
elif self.key < node.key:
if self.right is None:
self.right = node
node.parent = self
else:
self.right.insert(node)
def inorder(self):
if self.left is not None:
self.left.inorder()
print(self.key, end=' ')
if self.right is not None:
self.right.inorder()
def replace_node_of_parent(self, new_node):
if self.parent is not None:
if new_node is not None:
new_node.parent = self.parent
if self.parent.left == self:
self.parent.left = new_node
elif self.parent.right == self:
self.parent.right = new_node
else:
self.key = new_node.key
self.left = new_node.left
self.right = new_node.right
if new_node.left is not None:
new_node.left.parent = self
if new_node.right is not None:
new_node.right.parent = self
def find_min(self):
current = self
while current.left is not None:
current = current.left
return current
def remove(self):
if (self.left is not None and self.right is not None):
successor = self.right.find_min()
self.key = successor.key
successor.remove()
elif self.left is not None:
self.replace_node_of_parent(self.left)
elif self.right is not None:
self.replace_node_of_parent(self.right)
else:
self.replace_node_of_parent(None)
def search(self, key):
if self.key > key:
if self.left is not None:
return self.left.search(key)
else:
return None
elif self.key < key:
if self.right is not None:
return self.right.search(key)
else:
return None
return self
class BSTree:
def __init__(self):
self.root = None
def inorder(self):
if self.root is not None:
self.root.inorder()
def add(self, key):
new_node = BSTNode(key)
if self.root is None:
self.root = new_node
else:
self.root.insert(new_node)
def remove(self, key):
to_remove = self.search(key)
if (self.root == to_remove
and self.root.left is None and self.root.right is None):
self.root = None
else:
to_remove.remove()
def search(self, key):
if self.root is not None:
return self.root.search(key)
bstree = BSTree()
print('Menu (this assumes no duplicate keys)')
print('add <key>')
print('remove <key>')
print('inorder')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
key = int(do[1])
bstree.add(key)
elif operation == 'remove':
key = int(do[1])
bstree.remove(key)
elif operation == 'inorder':
print('Inorder traversal: ', end='')
bstree.inorder()
print()
elif operation == 'quit':
break
Output:
case 1:
Menu (this assumes no duplicate keys)
add <key>
remove <key>
inorder
quit
What would you like to do? add 5
What would you like to do? add 1
What would you like to do? add 10
What would you like to do? add 7
What would you like to do? add 3
What would you like to do? inorder
Inorder traversal: 1 3 5 7 10
What would you like to do? remove 3
What would you like to do? remove 7
What would you like to do? inorder
Inorder traversal: 1 5 10
What would you like to do? remove 5
What would you like to do? inorder
Inorder traversal: 1 10
What would you like to do? quit
Case 2:
Menu (this assumes no duplicate keys)
add <key>
remove <key>
inorder
quit
What would you like to do? add 2
What would you like to do? add 8
What would you like to do? inorder
Inorder traversal: 2 8
What would you like to do? add 5
What would you like to do? inorder
Inorder traversal: 2 5 8
What would you like to do? remove 2
What would you like to do? remove 8
What would you like to do? inorder
Inorder traversal: 5
What would you like to do? remove 5
What would you like to do? inorder
Inorder traversal:
What would you like to do? quit
Result:
Thus, the binary search tree program of varies operation was executed and verified
Ex. No:10A
Date:
Write a program to implement the tree traversal methods.
Preorder traversal
Aim:
To write a Python program for preorder traverse to search element from binary tree.
Program:
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert Node
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the Tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
# Preorder traversal
# Root -> Left ->Right
def PreorderTraversal(self, root):
res = []
if root:
res.append(root.data)
res = res + self.PreorderTraversal(root.left)
res = res + self.PreorderTraversal(root.right)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.PreorderTraversal(root))
Output:
[27, 14, 10, 19, 35, 31, 42]
Result:
Thus, the preorder traversal program was executed and verified
Ex. No:10B
Date:
Write a program to implement the tree traversal methods.
Postorder traversal
Aim:
To write a Python program for post-order traversal to search element from binary tree.
Program:
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert Node
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the Tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
# Postorder traversal
# Left ->Right -> Root
def PostorderTraversal(self, root):
res = []
if root:
res = self.PostorderTraversal(root.left)
res = res + self.PostorderTraversal(root.right)
res.append(root.data)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.PostorderTraversal(root))
Output:
[10, 19, 14, 31, 42, 35, 27]
Result:
Thus, the postorder traversal program was executed and verified
Ex. No:11
Date:
Write a program to perform the following operations: a) Insert an element into an AVL tree. b)
Delete an element from an AVL tree. c) Search for a key element in a AVL tree
Aim:
To write a Python program to implement AVL Tree.
Program:
import sys
# Create a tree node
class TreeNode(object):
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
class AVLTree(object):
# Function to insert a node
def insert_node(self, root, key):
# Find the correct location and insert the node
if not root:
return TreeNode(key)
elif key < root.key:
root.left = self.insert_node(root.left, key)
else:
root.right = self.insert_node(root.right, key)
root.height = 1 + max(self.getHeight(root.left),
self.getHeight(root.right))
# Update the balance factor and balance the tree
balanceFactor = self.getBalance(root)
if balanceFactor > 1:
if key < root.left.key:
return self.rightRotate(root)
else:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)
if balanceFactor < -1:
if key > root.right.key:
return self.leftRotate(root)
else:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
# Function to delete a node
def delete_node(self, root, key):
# Find the node to be deleted and remove it
if not root:
return root
elif key < root.key:
root.left = self.delete_node(root.left, key)
elif key > root.key:
root.right = self.delete_node(root.right, key)
else:
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
temp = self.getMinValueNode(root.right)
root.key = temp.key
root.right = self.delete_node(root.right,
temp.key)
if root is None:
return root
# Update the balance factor of nodes
root.height = 1 + max(self.getHeight(root.left),
self.getHeight(root.right))
balanceFactor = self.getBalance(root)
# Balance the tree
if balanceFactor > 1:
if self.getBalance(root.left) >= 0:
return self.rightRotate(root)
else:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)
if balanceFactor < -1:
if self.getBalance(root.right) <= 0:
return self.leftRotate(root)
else:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
# Function to perform left rotation
def leftRotate(self, z):
y = z.right
T2 = y.left
y.left = z
z.right = T2
z.height = 1 + max(self.getHeight(z.left),
self.getHeight(z.right))
y.height = 1 + max(self.getHeight(y.left),
self.getHeight(y.right))
return y
# Function to perform right rotation
def rightRotate(self, z):
y = z.left
T3 = y.right
y.right = z
z.left = T3
z.height = 1 + max(self.getHeight(z.left),
self.getHeight(z.right))
y.height = 1 + max(self.getHeight(y.left),
self.getHeight(y.right))
return y
# Get the height of the node
def getHeight(self, root):
if not root:
return 0
return root.height
# Get balance factore of the node
def getBalance(self, root):
if not root:
return 0
return self.getHeight(root.left) - self.getHeight(root.right)
def getMinValueNode(self, root):
if root is None or root.left is None:
return root
return self.getMinValueNode(root.left)
def preOrder(self, root):
if not root:
return
print("{0} ".format(root.key), end="")
self.preOrder(root.left)
self.preOrder(root.right)
# Print the tree
def printHelper(self, currPtr, indent, last):
if currPtr != None:
sys.stdout.write(indent)
if last:
sys.stdout.write("R----")
indent += " "
else:
sys.stdout.write("L----")
indent += "| "
print(currPtr.key)
self.printHelper(currPtr.left, indent, False)
self.printHelper(currPtr.right, indent, True)
myTree = AVLTree()
root = None
nums = [33, 13, 52, 9, 21, 61, 8, 11]
for num in nums:
root = myTree.insert_node(root, num)
myTree.printHelper(root, "", True)
key = 13
root = myTree.delete_node(root, key)
print("After Deletion: ")
myTree.printHelper(root, "", True)
Output:
R----33
L----13
| L----9
| | L----8
| | R----11
| R----21
R----52
R----61
After Deletion:
R----33
L----9
| L----8
| R----21
| L----11
R----52
R----61
Result:
Thus, the AVL tree program was executed and verified
Ex. No:12A
Date:
Write a program to perform DFS of Graph using Graph ADT.
Aim:
To write a Python program to implement depth first search.
Program:
from collections import defaultdict
class Graph:
# Constructor
def __init__(self):
# Default dictionary to store graph
self.graph = defaultdict(list)
# Function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# A function used by DFS
def DFSUtil(self, v, visited):
# Mark the current node as visited
# and print it
visited.add(v)
print(v, end=' ')
# Recur for all the vertices
# adjacent to this vertex
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)
# The function to do DFS traversal. It uses
# recursive DFSUtil()
def DFS(self, v):
# Create a set to store visited vertices
visited = set()
# Call the recursive helper function
# to print DFS traversal
self.DFSUtil(v, visited)
# Driver's code
if __name__ == "__main__":
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is Depth First Traversal (starting from vertex 2)")
# Function call
g.DFS(2)
Output:
Following is Depth First Traversal (starting from vertex 2)
2013
Result:
Thus, the DFS program was executed and verified
Ex. No:12B
Date:
Write a program to perform BFS of Graph using Graph ADT.
Aim:
To write a Python program perform Breadth First Search.
Program:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def BFS(self, s):
visited = [False] * (max(self.graph) + 1)
queue = []
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0)
print(s, end=" ")
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
if __name__ == '__main__':
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is Breadth First Traversal"
" (starting from vertex 2)")
g.BFS(2)
Output:
Following is Breadth First Traversal (starting from vertex 2)
2031
Result:
Thus, the BFS program was executed and verified
Ex. No:13
Date:
Write a program to find the shortest path using Graph ADT using graph algorithms
Aim:
To write a Python program to implement shortest path algorithm.
Algorithm:
1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree,
i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty.
2) Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE.
Assign distance value as 0 for the source vertex so that it is picked first.
3) While sptSet doesn’t include all vertices:
• Pick a vertex u which is not there in sptSet and has minimum distance value.
• Include u to sptSet.
• Update distance value of all adjacent vertices of u. To update the distance values, iterate through all
adjacent vertices. For every adjacent vertex v, if the sum of a distance value of u (from source) and
weight of edge u-v, is less than the distance value of v, then update the distance value of v.
Program:
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
def printSolution(self, dist):
print("Vertex \t Distance from Source")
for node in range(self.V):
print(node, "\t\t", dist[node])
def minDistance(self, dist, sptSet):
# Initialize minimum distance for next node
min = 1e7
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index
def dijkstra(self, src):
dist = [1e7] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
u = self.minDistance(dist, sptSet)
sptSet[u] = True
for v in range(self.V):
if (self.graph[u][v] > 0 and
sptSet[v] == False and
dist[v] > dist[u] + self.graph[u][v]):
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
g.dijkstra(0)
Output:
Vertex Distance from Source
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
Result:
Thus, the Shortest path algorithm was executed and verified