CD3291 Data Structurres and Algorithm Lab Manual
CD3291 Data Structurres and Algorithm Lab Manual
1
(c)Hashing with double hashing
9 TREE REPRESENTATION AND TRAVERSAL
ALGORITHM
(a)Array representation
(b)Linkedlist representation
(c) Traversal algorithm
10 IMPLEMENTATION OF BINARY SEARCH TREE
(a) Binary search tree
(b) AVL tree
11 IMPLEMENTATION OF HEAPS
(a) MAX heap
(b) MIN heap
12 GRAPH REPRESENTATION AND TRAVERSAL
ALGORITHM
(a)GRAPH REPRESENTATION—ADJACENCY LIST
(b)GRAPH REPRESNTATION—ADJACENCY MATRIX
(c) TRAVERSAL ALGORITHM—BFS
(d) TRAVERSAL ALGORITHM—DFS
13 SINGLE SOURCE SHORTEST PATH ALGORITHM
14 MINIMUM SPANNING TREE ALGORITHM
2
Ex.No: 1 ADTS AS PYTHON CLASSES
Date:
Aim:
Algorithm:
Step1: Select the structure chosen by the user as 1 for stack and 2 for queue.
Step 2: If press 1, it will call class Stack.
Step 3: It will keep on checking till n1 becomes 5.
Step 4: If press 1, accept from the user values and it will store in the stack.
Step 5: If press 2, it will remove value from the stack
Step 6: If press 3, it will show the size of the stack.
Step 7: If press 4, it will show items of the stack.
Step 8: If press 2, it will call class Queue.
Step 9: Accept from the user 1. 1.enqueue 2.dequeue 3.size 4.display 5.exit
Step 10: It will keep on checking till n1 becomes 5.
Step 11: If press 1, accept from the user values and it will store in enqueue.
Step 12: If press 2, it will perform dequeue and display the message dequeue done.
Step 13: If press 3, it will show the size of the queue.
Step 14: if press 4, it will show items of the queue
3
Program: class Stack:
def init (self):
self.items = []
def isEmpty(self):
return self.items == [] def
push(self, item):
self.items.append(item) def
pop(self):
return self.items.pop() def
peek(self):
return self.items[len(self.items) - 1] def size(self):
return len(self.items)
#Queue ADT
class Queue:
def init (self):
self.items = []
def isEmpty(self):
return self.items == [] def
enqueue(self,item):
self.items.append(item) def
dequeue(self):
return self.items.pop(0) def
front(self):
return self.items[len(self.items)-1] def
size(self):
return len(self.items) #
STack ADT operation example
s=Stack()
print('Stack operation examples')
print(s.isEmpty())
s.push(5)
s.push('python')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(11.5)
print(s.pop())
4
print(s.size())
# Queue ADT operation example
q=Queue()
print('Queue operation examples')
print(q.isEmpty())
q.enqueue(5)
q.enqueue('python')
print(q.front())
q.enqueue(True)
print(q.size())
print(q.isEmpty())
q.enqueue(11.5)
print(q.dequeue())
print(q.dequeue())
print(q.size())
5
OUTPUT:
Result:
Thus the given program has been executed and verified successfully.
6
Ex.No: 2(a) IMPLEMENT RECURSIVE ALGORITHMS IN PYTHON
Date:
Aim:
Algorithm:
1. Create a tower_of_hanoi recursive function and pass two arguments: the number of disks n and the
name of the rods such as source, auxiliary, and target.
2. define the base case when the number of disks is 1. In this case, simply move the one disk from
the source to target and return.
3. Now, move remaining n-1 disks from source to auxiliary using the target as the auxiliary.
4. Then, the remaining 1 disk move on the source to target.
5. Move the n-1 disks on the auxiliary to the target using the source as the auxiliary.
Program:
if(disks == 1):
return
print('Move disk {} from rod {} to rod {}.'.format(disks, source, target)) tower_of_hanoi(disks - 1, auxiliary,
source, target)
disks = int(input('Enter the number of disks: ')) tower_of_hanoi(disks, 'A', 'B', 'C')
Output:
7
Ex.No: 2(b) Fibbonaci series
Date:
Aim:
Algorithm:
Program:
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 5
if nterms <= 0:
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
output
Fibonacci sequence:
0
1
1
2
3
8
Factorial of a number
Ex.No: 2(c)
Date:
Aim:
Algorithm:
Program:
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 5
if num < 0:
elif num == 0:
else:
output:
Result:
Thus the given program has been executed and verified successfully.
9
Ex.No: 3 LIST ADT USING PYTHON ARRAYS
Date:
Aim:
Algorithm:
Program:
class Student:
def init (self, name, rollno, m1, m2):
self.name = name
self.rollno = rollno
self.m1 = m1
self.m2 = m2
def accept(self, Name, Rollno, marks1, marks2 ):
ob = Student(Name, Rollno, marks1, marks2 )
ls.append(ob)
def display(self, ob):
print("Name : ", ob.name)
print("RollNo : ", ob.rollno)
print("Marks1 : ", ob.m1)
print("Marks2 : ", ob.m2)
print("\n")
def search(self, rn):
for i in range(ls. len ()):
if(ls[i].rollno == rn):
return i
def delete(self, rn):
i = obj.search(rn)
del ls[i]
def update(self, rn, No):
i = obj.search(rn)
roll = No
ls[i].rollno = roll;
ls =[]
obj = Student('', 0, 0, 0)
print("\nOperations used, ")
10
print("\n1.Accept Student details\n2.Display Student Details\n" "3.Search Details of a Student\n4.Delete Details of
Student" "\n5.Update Student Details\n6.Exit")
# ch = int(input("Enter choice:"))
# if(ch == 1):
obj.accept("A", 1, 100, 100)
obj.accept("B", 2, 90, 90)
obj.accept("C", 3, 80, 80)
# elif(ch == 2):
print("\n")
print("\nList of Students\n")
for i in range(ls. len ()):
obj.display(ls[i])
# elif(ch == 3):
print("\n Student Found, ")
s = obj.search(2)
obj.display(ls[s])
# elif(ch == 4):
obj.delete(2)
print(ls. len ())
print("List after deletion")
for i in range(ls. len ()):
obj.display(ls[i])
# elif(ch == 5):
obj.update(3, 2)
print(ls. len ())
print("List after updation")
for i in range(ls. len ()):
obj.display(ls[i])
# else:
print("")
output:
Operations used,
1. Accept Student details
List of Students
Name :A
RollNo : 1
Marks1 :100
Marks2 :100
Name: B
RollNo : 2
Marks1 : 90
Marks2 : 90
Name : C
RollNo : 3
Marks1 : 80
Marks2 : 80
11
Student Found,
Name : B
RollNo : 2
Marks1 : 90
Marks2 : 90
Name : C
RollNo : 3
Marks1 : 80
Marks2 : 80
Name : C
RollNo : 2
Marks1 : 80
Marks2 : 8
Result:
12
Ex.No: 4(a) LINKED LIST IMPLEMENTATION
Date:
Aim:
Algorithm:
1. Defining the Node class which actually holds the data as well as the next element link
2. Defining the Linked List class
3. Initializing the Linked List constructor with head variable
4. Defining the insert() method which is used to add elements to the Singly Linked List
a. Checking whether or not the Linked List is empty
b. Adding a Node to the beginning of the Linked List
c. Adding a Node to the end of the Linked List
d. Adding a Node in the middle of the Linked List
5. Defining the delete() method which is used to delete elements from the Singly Linked List
a. Checking whether or not the Linked List is empty or not, or deleting the last element in the
Linked List
b. Deleting the first element of the Linked List
c. Deleting the last element of the Linked List
d. Deleting an element by position or by value
6. Defining the display() method which is used to present the Singly Linked List in a user-
comprehendible form
Program:
class Node:
def init (self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def init (self):
self.headval = None
def AtBegining(self,newdata):
NewNode = Node(newdata)
NewNode.nextval = self.headval s
elf.headval = NewNode
def AtEnd(self, newdata):
NewNode = Node(newdata)
if self.headval is None:
self.headval = NewNode
return
laste = self.headval
while(laste.nextval):
laste = laste.nextval
laste.nextval=NewNode
def Inbetween(self,middle_node,newdata):
if middle_node is None:
13
print("The mentioned node is absent")
return
NewNode = Node(newdata)
NewNode.nextval = middle_node.nextval
middle_node.nextval = NewNode
def search_item(self, x):
if self.headval is None:
print("List has no elements")
return
n = self.headval
while n is not None:
if n.dataval == x:
print("Item found")
return True n =
n.nextval
print("item not found")
return False
def getCount(self):
temp = self.headval # Initialise temp
count = 0 # Initialise count
while (temp):
count += 1
temp = temp.nextval
return count
def RemoveNode(self, Removekey):
HeadVal = self.headval
if (HeadVal is not None):
if (HeadVal.dataval == Removekey):
self.headval = HeadVal.nextval
HeadVal = None
return
while (HeadVal is not None):
if HeadVal.dataval == Removekey:
break
prev = HeadVal
HeadVal = HeadVal.nextval
if (HeadVal == None):
return
prev.nextval = HeadVal.nextval
HeadVal = None
def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval
list = SLinkedList()
list.headval = Node("1")
e2 = Node("2")
e3 = Node("3")
list.headval.nextval = e2
e2.nextval = e3
list.AtBegining("4")
list.AtEnd("5")
list.Inbetween(list.headval.nextval,"6")
list.search_item("3")
14
print ("Count of nodes is :",list.getCount())
list.RemoveNode("2")
list.listprint()
output:
Item found
Count of nodes is : 6 4
1
6
2
3
5
after removing 4
1
6
3
5
Result:
Thus the given program has been executed and verified successfully.
15
Ex.No: 4(b) Doubly linked list
Date:
Aim:
Algorithm:
1. Defining the Node class which actually holds the data, previous and next element link
2. Defining the Linked List class
3. Initializing the Linked List constructor with head variable
4. Defining the insert() method which is used to add elements to the doubly Linked List
e. Checking whether or not the Linked List is empty
f. Adding a Node to the beginning of the Linked List
g. Adding a Node to the end of the Linked List
h. Adding a Node in the middle of the Linked List
5. Defining the delete() method which is used to delete elements from the doubly Linked List
a. Checking whether or not the Linked List is empty or not, or deleting the last element in the
Linked List
b. Deleting the first element of the Linked List
c. Deleting the last element of the Linked List
d. Deleting an element by position or by value
6. Defining the display() method which is used to present the doubly Linked List in a
user- comprehendible form
Program:
class Node:
self.start_node = new_node
def insert_at_end(self, data):
if self.start_node is None:
new_node = Node(data)
self.start_node = new_node
return
n = self.start_node
while n.nref is not None:
n = n.nref
new_node = Node(data)
n.nref = new_node
new_node.pref = n
def insert_after_item(self, x, data):
if self.start_node is None:
print("List is empty")
return
else:
n = self.start_node
while n is not None:
if n.item == x:
break
n = n.nref
if n is None:
print("item not in the list")
else:
new_node = Node(data)
new_node.pref = n
new_node.nref = n.nref
if n.nref is not None:
n.nref.prev = new_node
n.nref = new_node
def insert_before_item(self, x, data):
if self.start_node is None:
print("List is empty")
return
else:
n = self.start_node
while n is not None:
if n.item == x:
break
n = n.nref
if n is None:
print("item not in the list")
else:
new_node = Node(data)
new_node.nref = n
new_node.pref = n.pref
if n.pref is not None:
n.pref.nref = new_node
n.pref = new_node
def traverse_list(self):
if self.start_node is None:
print("List has no element")
17
return
else:
n = self.start_node
while n is not None:
print(n.item , " ")
n = n.nref
def delete_at_start(self):
if self.start_node is None:
print("The list has no element to delete")
return
if self.start_node.nref is None:
self.start_node = None
return
self.start_node = self.start_node.nref
self.start_prev = None;
def delete_at_end(self):
if self.start_node is None:
print("The list has no element to delete")
return
if self.start_node.nref is None:
self.start_node = None
return
n = self.start_node
while n.nref is not None:
n = n.nref
n.pref.nref = None
def delete_element_by_value(self, x):
if self.start_node is None:
print("The list has no element to delete")
return
if self.start_node.nref is None:
if self.start_node.item == x:
self.start_node = None
else:
print("Item not found")
return
if self.start_node.item == x:
self.start_node = self.start_node.nref
self.start_node.pref = None
return
n = self.start_node
while n.nref is not None:
if n.item == x:
break;
n = n.nref
if n.nref is not None:
n.pref.nref = n.nref
n.nref.pref = n.pref
else:
if n.item == x:
n.pref.nref = None else:
print("Element not found")
new_linked_list = DoublyLinkedList()
new_linked_list.insert_in_emptylist(50)
18
new_linked_list.insert_at_start(10)
new_linked_list.insert_at_start(5)
print(new_linked_list.traverse_list())
new_linked_list.insert_at_end(29)
new_linked_list.insert_at_end(39)
print(new_linked_list.traverse_list())
new_linked_list.insert_after_item(50, 65)
print(new_linked_list.traverse_list())
new_linked_list.insert_before_item(29, 100)
print(new_linked_list.traverse_list())
new_linked_list.delete_at_start()
print(new_linked_list.traverse_list())
new_linked_list.delete_at_end()
print(new_linked_list.traverse_list())
new_linked_list.delete_element_by_value(65)
print(new_linked_list.traverse_list())
output:
5
10
50
None
5
10
50
29
39
None
5
10
50
65
29
39
None
5
10
50
100
29
39
None
10
50
100
29
39
None
10
50
100
29
None
19
Element not found 10
50
100
29
None
Result:
Thus the given program has been executed and verified successfully.
20
Ex.No: 4(c)
Circular singly linked list
Date:
Aim:
Algorithm:
1. Defining the Node class which actually holds the data as well as next element link
2. Defining the Linked List class
3. Initializing the Linked List constructor with head variable
4. Defining the insert() method which is used to add elements to the circular singly Linked List
i. Checking whether or not the Linked List is empty
j. Adding a Node to the beginning of the Linked List
k. Adding a Node to the end of the Linked List
l. Adding a Node in the middle of the Linked List
5. Defining the delete() method which is used to delete elements from the circular singly Linked List
a. Checking whether or not the Linked List is empty or not, or deleting the last element in the
Linked List
b. Deleting the first element of the Linked List
c. Deleting the last element of the Linked List
d. Deleting an element by position or by value
6. Defining the display() method which is used to present the circular singly Linked List in a user-
comprehendible form
Program:
class Node:
21
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)
22
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:
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 4 at beg The list: 4 5
What would you like to do? insert 9 at end The list: 4 5 9
What would you like to do? insert 6 after 1 The list: 4 5 6 9
What would you like to do? insert 7 after 6 No such index.
The list: 4 5 6 9
What would you like to do? insert 8 before 2 The list: 4 5 8 6 9
What would you like to do? remove 4 The list: 4 5 8
6
What would you like to do? remove 7 No such
index.
The list: 4 5 8 6
What would you like to do? remove 0 The list: 5 8 6
What would you like to do? remove 1 The list: 5 6
What would you like to do? quit
Result:
Thus the given program has been executed and verified successfully.
23
Ex.No: 4(c) Circular doubly linked list
Date:
Aim:
Algorithm:
1. Defining the Node class which actually holds the data as well as next element link
2. Defining the Linked List class
3. Initializing the Linked List constructor with head variable
4. Defining the insert() method which is used to add elements to the circular doubly Linked List
m. Checking whether or not the Linked List is empty
n. Adding a Node to the beginning of the Linked List
o. Adding a Node to the end of the Linked List
p. Adding a Node in the middle of the Linked List
5. Defining the delete() method which is used to delete elements from the circular doubly Linked List
a. Checking whether or not the Linked List is empty or not, or deleting the last element in the
Linked List
b. Deleting the first element of the Linked List
c. Deleting the last element of the Linked List
d. Deleting an element by position or by value
6. Defining the display() method which is used to present the circular doubly Linked List in a user-
comprehendible form
Program:
class Node:
def init (self, data):
self.data = data
self.next = None
self.prev = None
class CircularDoublyLinkedList:
def init (self):
self.first = None
def get_node(self, index):
current = self.first
for i in range(index):
current = current.next
if current == self.first:
return None
return current
def insert_after(self, ref_node, new_node):
new_node.prev = ref_node
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):
self.insert_after(ref_node.prev, new_node)
def insert_at_end(self, new_node):
24
if self.first is None:
self.first = new_node
new_node.next = new_node
new_node.prev = new_node
else:
self.insert_after(self.first.prev, new_node)
def insert_at_beg(self, new_node):
self.insert_at_end(new_node)
self.first = new_node
def remove(self, node):
if self.first.next == self.first:
self.first = None
else:
node.prev.next = node.next
node.next.prev = node.prev
if self.first == node:
self.first = node.next
def display(self):
if self.first is None:
return
current = self.first
while True:
print(current.data, end = ' ')
current = current.next
if current == self.first:
break
a_cdllist = CircularDoublyLinkedList()
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_cdllist.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_cdllist.insert_at_beg(new_node)
elif position == 'end':
a_cdllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_cdllist.get_node(index)
if ref_node is None:
print('No such index.')
continue
25
if suboperation == 'after':
a_cdllist.insert_after(ref_node, new_node)
output:
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 at end
The list: 1 3
What would you like to do? insert 2 before 1 The list: 1 2 3
What would you like to do? insert 4 after 2 The list: 1 2 3 4
What would you like to do? insert 0 at beg The list: 0 1 2 3 4
What would you like to do? remove 2 The list: 0 1 3 4
what would you like to do? Quit
Result:
Thus the given program has been executed and verified successfully.
26
Ex.No: 5 STACK AND QUEUE IMPLEMENTATION
Date:
Aim:
To write a program to implement stack using linked list
Algorithm
Program:
class Node:
def init (self, data=None, next=None):
self.data = data
self.next = next
class Stack:
def init (self):
self.top = None
def push(self, data):
if self.top is None:
self.top = Node(data, None)
return
self.top = Node(data, self.top)
def pop(self):
if self.top is None:
return
temp = self.top
if self.top is not None:
self.top = self.top.next
temp.next = None
return temp.data
def peek(self):
return self.top.data
def clearstack(self):
self.top = None
def emptystack(self):
if self.top is None:
return True
return False
def display(self):
itr = self.top
sstr = ' '
while itr:
sstr += str(itr.data) + '-->'
27
itr = itr.next
print(sstr)
if name == " main ":
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(40)
stack.peek()
stack.display()
stack.pop()
stack.push(30)
Output:
Result:
Thus the given program has been executed and verified successfully.
28
Ex.No: 5(b) QUEUE IMPLEMENTATION
Date:
Aim:
Algorithm:
1. Create a newNode with the given value and set the node's pointer to NULL.
2. Check whether queue is EMPTY.
3. If it is EMPTY, set FRONT and REAR to newNode.
4. Else, set the pointer of REAR to newNode and make REAR as the newNode.
5. Check if the queue is EMPTY.
6. If it is EMPTY, then display "EMPTY QUEUE" and exit.
7. Else, create a temporary node and set it to FRONT.
8. Make the next node as FRONT and delete the temporary node.
9. Display the nodes in queue
Program:
class Node:
def init (self, data=None, next=None, prev=None):
self.data = data #creating a storage for assigning value
self.next = next #pointer to the next value
self.prev = prev #pointer to the already existing previous value.
class Queue:
def init (self):
self.front = self.rear = None
def enqueue(self, data):
if self.rear is None:
self.front = self.rear = Node(data, None)
return
self.rear.next = Node(data, None)
self.rear.next.prev = self.rear
self.rear = self.rear.next
def dequeue(self):
if self.front is None:
raise Exception('empty queue')
temp = self.front.data
self.front = self.front.next
if self.front is None:
self.rear = None
return
self.front.prev = None
return temp
def clearqueue(self):
self.front = self.rear = None
def emptyqueue(self):
if self.front is None:
return True
return False
def display(self):
itr = self.front
29
sstr = ' '
while itr:
sstr += str(itr.data) + '-->'
itr = itr.next
print(sstr)
if name == " main ":
queue = Queue()
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
queue.display()
queue.dequeue()
#queue.dequeue()
#queue.dequeue()
queue.display()
queue.enqueue(40)
queue.enqueue(50)
queue.enqueue(60)
queue.display()
queue.clearqueue()
queue.display()
output:
insertion
10-->20-->30-->
after deletion 20--
>30-->
20-->30-->40-->50-->60-->
queue is empty
Result:
Thus the given program has been executed and verified successfully.
30
Ex.No: 6(a) APPLICATIONS OF LIST, STACK AND QUEUE ADT’s
Date:
Aim:
Algorithm:
Program:
A=[]
n=int(input("Enter N for N x N matrix : "))
print("Enter the element ::>")
for i in range(n):
row=[]
for j in range(n):
row.append(int(input()))
A. append(row)
print(A)
print("Display Array In Matrix Form")
for i in range(n):
for j in range(n):
print(A[i][j], end=" ")
print()
B=[]
n=int(input("Enter N for N x N matrix : "))
print("Enter the element ::>")
for i in range(n):
row=[]
for j in range(n):
row.append(int(input()))
B. append(row)
print(B)
print("Display Array In Matrix Form")
for i in range(n):
for j in range(n):
print(B[i][j], end=" ")
print()
31
result = [[0,0,0], [0,0,0], [0,0,0]]
for i in range(n):
for j in range(len(A[0])):
result[i][j] = A[i][j] + B[i][j]
print("Resultant Matrix is ::>")
for r in result:
print("Resultant Matrix is ::>",r)
for i in range(n):
for j in range(len(A[0])):
result[i][j] = A[i][j] - B[i][j]
print("Resultant Matrix is ::>")
for r in result:
print("Resultant Matrix is ::>",r)
for i in range(n):
for j in range(len(A[0])):
result[i][j] = A[i][j] * B[i][j]
print("Resultant Matrix is ::>")
for r in result:
print("Resultant Matrix is ::>",r)
for i in range(n):
for j in range(n):
result[i][j] = result[j][i]
for r in result:
print("Resultant Matrix is ::>",r)
for i in range(n):
for j in range(len(A[0])):
result[i][j] = A[i][j] % B[i][j]
print("Resultant Matrix is ::>")
for r in result:
print("Resultant Matrix is ::>",r)
Output
32
8
9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Result:
Thus the given program has been executed and verified successfully.
33
Ex.No: 6(b)
APPLICATIONS OF STACK
Date:
Aim:
Algorithm:
Program:
34
output:
Result:
Thus the given program has been executed and verified successfully.
35
Ex.No: 6(b) Application of queue
Date:
Aim:
Algorithm:
Program:
from collections import deque
class Queue:
def init (self):
self.s1 = deque()
self.s2 = deque()
def enqueue(self, data):
while len(self.s1):
self.s2.append(self.s1.pop())
self.s1.append(data)
while len(self.s2):
self.s1.append(self.s2.pop())
def dequeue(self):
if not self.s1:
print("Underflow!!")
exit(0)
return self.s1.pop()
if name == ' main ':
keys = [1, 2, 3, 4, 5]
q = Queue()
for key in keys:
q.enqueue(key)
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
output:
1
2
3
4
5
Result:
Thus the given program has been executed and verified successfully.
36
Ex.No: 7(a) BUBBLE SORT
Date:
Aim:
To write a program to implement sorting algorithm
Algorithm
Program
def bubbleSort(arr):
n = len(arr)
for i in range(n-1):
output:
37
Ex.No: 7(b) SELECTION SORT
Date:
Aim:
To write a program to implement sorting algorithm
Algorithm:
Program:
import sys
A = [5,3,8,6,7,2]
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
print(A)
print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i]),
output:
Sorted array
[2, 3, 5, 6, 7, 8]
38
Ex.No: 7(c) INSERTION SORT
Date:
Aim:
To write a program to implement sorting algorithm
Algorithm:
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
print(arr)
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])
output:
39
Ex.No: 7(c) QUICK SORT
Date:
Aim:
To write a program to implement sorting algorithm
Algorithm:
1. Select the Pivot Element as first, last, random and median element
2. Rearrange the Array
a. A pointer is fixed at the pivot element. The pivot element is compared with the elements
beginning from the first index.
b. If the element is greater than the pivot element, a second pointer is set for that element.
c. Now, pivot is compared with other elements. If an element smaller than the pivot element is
reached, the smaller element is swapped with the greater element found earlier.
d. Again, the process is repeated to set the next greater element as the second pointer. And, swap
it with another smaller element.
e. The process goes on until the second last element is reached.
f. Finally, the pivot element is swapped with the second pointer
3. Divide Subarrays
g. Pivot elements are again chosen for the left and the right sub-parts separately. And, step 2 is
repeated.
h. The subarrays are divided until each subarray is formed of a single element. At this point, the
array is sorted.
Program:
40
if right < left:
break
else:
n=len(list1)
quicksort(list1, 0, n-1)
print(list1)
Output:
sorted array is
[17, 26, 31, 44, 56, 93]
Result:
Thus the given program has been executed and verified successfully.
43
Ex.No: 7(d) MERGE SORT
Date:
Aim:
To write a program to implement sorting algorithm
Algorithm:
Program:
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i=j=k=0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
if name == ' main ':
arr = [38, 27, 43, 3, 9, 82, 10]
print("Given array is", end="\n")
printList(arr)
mergeSort(arr)
44
print("Sorted array is: ", end="\n")
printList(arr)
Output:
Given array is
38 27 43 3 9 82 10
Sorted array is:
3 9 10 27 38 43 82
45
Ex.No: 7(e) SEARCHING ALGORITHM
Date:
Aim:
1) LINEAR SEARCH
Algorithm:
Program:
Output:
46
2) BINARY SEARCH
Algorithm:
Program:
output:
Result:
Thus the given program has been executed and verified successfully.
47
Ex.No: 8(a) HASHING WITH LINEAR PROBING
Date:
Aim:
Algorithm:
Program:
class hashTable:
def init (self):
self.size = int(input("Enter the Size of the hash table : "))
self.table = list(0 for i in range(self.size))
self.elementCount = 0
self.comparisons = 0
def isFull(self):
if self.elementCount == self.size:
return True
else:
return False
def hashFunction(self, element):
return element % self.size
def insert(self, element):
# checking if the table is full
if self.isFull():
print("Hash Table Full")
return False
isStored = False
position = self.hashFunction(element)
48
if self.table[position] == 0:
self.table[position] = element
print("Element " + str(element) + " at position " + str(position))
isStored = True
self.elementCount += 1
else:
print("Collision has occured for element " + str(element) + " at position " + str(position) + " finding new
Position.")
while self.table[position] != 0: position += 1
if position >= self.size:
position = 0
self.table[position] = element
isStored = True
self.elementCount += 1
return isStored
def search(self, element):
found = False
position = self.hashFunction(element)
self.comparisons += 1
if(self.table[position] == element):
return position
isFound = True
else:
temp = position - 1
while position < self.size:
if self.table[position] != element:
position += 1
self.comparisons += 1
else:
return position
position = temp
while position >= 0:
if self.table[position] != element:
position -= 1
self.comparisons += 1
else:
return position
if not found:
print("Element not found")
return False
def remove(self, element):
position = self.search(element)
if position is not False:
self.table[position] = 0
print("Element " + str(element) + " is Deleted")
self.elementCount -= 1
else:
print("Element is not present in the Hash Table")
return
def display(self):
print("\n")
for i in range(self.size):
print(str(i) + " = " + str(self.table[i]))
print("The number of element is the Table are : " + str(self.elementCount))
49
table1 = hashTable()
table1.insert(89)
table1.insert(18)
table1.insert(49)
table1.insert(58)
table1.insert(9)
table1.display()
print()
print("The position of element 9 is : " + str(table1.search(9)))
print("The position of element 58 is : " + str(table1.search(58)))
print("\nTotal number of comaprisons done for searching = " + str(table1.comparisons))
print()
table1.remove(18)
table1.display()
output
0= 49
1= 58
2= 9
3= 0
4= 0
5= 0
6= 0
7= 0
8= 0
9= 89
The number of element is the Table are : 4
Result:
Thus the given program has been executed and verified successfully.
50
Ex.No: 8(b) HASHING WITH QUADRATIC PROBING
Date:
Aim:
Algorithm:
Program:
class hashTable:
52
print("Element not Found")
return found
output:
0 = 49
1=0
2 = 58
3=9
4=0
5=0
6=0
7=0
8 = 18
9 = 89
53
The number of element is the Table are : 5
Deleted
0= 49
1= 0
2= 58
3= 9
4= 0
5= 0
6= 0
7= 0
8= 0
9= 89
The number of element is the Table are : 4
Result:
Thus the given program has been executed and verified successfully.
54
Ex.No: 8(c) HASHING WITH DOUBLE HASHING
Date:
Aim:
Algorithm:
Program:
class doubleHashTable:
def init (self):
self.size = int(input("Enter the Size of the hash table : "))
self.num = 7
self.table = list(0 for i in range(self.size))
self.elementCount = 0
self.comparisons = 0
def isFull(self):
if self.elementCount == self.size:
return True
else:
return False
def h1(self, element):
return element % self.size
55
def h2(self, element):
return (self.num-(element % self.num))
def doubleHashing(self, element, position):
posFound = False
limit = 50
i=1
while i <= limit:
newPosition = (self.h1(element) + i*self.h2(element)) % self.size
if self.table[newPosition] == 0:
posFound = True
break
else:
i += 1
return posFound, newPosition
def insert(self, element):
if self.isFull():
print("Hash Table Full")
return False
posFound = False
position = self.h1(element)
if self.table[position] == 0:
self.table[position] = element
print("Element " + str(element) + " at position " + str(position))
isStored = True
self.elementCount += 1
else:
while not posFound:
print("Collision has occured for element " + str(element) + " at position " + str(position) + " finding
new Position.")
posFound, position = self.doubleHashing(element, position) if posFound:
self.table[position] = element
self.elementCount += 1
return posFound
def search(self, element):
found = False
position = self.h1(element)
self.comparisons += 1
if(self.table[position] == element):
return position
else:
limit = 50
i=1
newPosition = position
while i <= limit:
position = (self.h1(element) + i*self.h2(element)) % self.size
self.comparisons += 1
if self.table[position] == element
found = True
break
elif self.table[position] == 0:
found = False
break
56
else:
57
5=0
6 = 49
7=0
8 = 18
9 = 89
The number of element is the Table are : 5
Result:
Thus the given program has been executed and verified successfully.
58
Ex.No: 9(a) ARRAY REPRESENTATION
Date:
Aim:
Algorithm:
Program:
tree = [None] * 20
def root(key):
if tree[0] != None:
print("Tree already had root")
else:
tree[0] = key
def set_left(key, parent):
if tree[parent] == None:
print("Can't set child at", (parent * 2) + 1, ", no parent found")
else:
tree[(parent * 2) + 1] = key
def set_right(key, parent):
if tree[parent] == None:
print("Can't set child at", (parent * 2) + 2, ", no parent found")
else:
tree[(parent * 2) + 2] = key def print_tree():
for i in range(20):
if tree[i] != None:
print(tree[i], end="")
else:
print("-", end="")
print()
root('3')
set_left('5', 0)
set_right('9', 0)
set_left('6', 1)
59
set_right('8', 1)
set_left('20', 2)
set_right('10', 2)
set_left('9', 5)
print_tree()
Output
Array representation
359682010 9
60
Ex.No: 9(a) LINKEDLIST REPRESENTATION
Date:
Aim:
Algorithm:
Program:
class Node:
def init (self,data):
self.data = data;
self.left = None;
self.right = None;
class BinaryTree:
def init (self):
self.root = None;
def insertNode(self, data):
newNode = Node(data);
if(self.root == None):
self.root = newNode;
return;
else:
queue = [];
queue.append(self.root);
while(True):
node = queue.pop(0);
if(node.left != None and node.right != None):
queue.append(node.left);
queue.append(node.right);
else:
if(node.left == None):
node.left = newNode;
queue.append(node.left);
else:
node.right = newNode;
queue.append(node.right);
break;
def inorderTraversal(self, node):
#Check whether tree is empty
if(self.root == None):
61
print("Tree is empty");
return;
else:
if(node.left != None):
self.inorderTraversal(node.left);
print(node.data),
if(node.right!= None):
self.inorderTraversal(node.right);
bt = BinaryTree();
bt.insertNode(1);
print("Binary tree after insertion");
bt.inorderTraversal(bt.root);
bt.insertNode(2);
bt.insertNode(3);
print("\nBinary tree after insertion");
bt.inorderTraversal(bt.root);
bt.insertNode(4);
bt.insertNode(5);
print("\nBinary tree after insertion");
bt.inorderTraversal(bt.root);
bt.insertNode(6);
bt.insertNode(7);
print("\nBinary tree after insertion");
bt.inorderTraversal(bt.root);
Output:
62
Ex.No: 9(b) TRAVERSAL ALGORITHM
Date:
Aim:
Algorithm:
Program:
class Node:
def init (self, data):
self.left = None
self.right = None
self.data = data
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
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
def inorderTraversal(self, root):
res = []
if root:
63
res = self.inorderTraversal(root.left)
res.append(root.data)
res = res + self.inorderTraversal(root.right)
return res
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
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.inorderTraversal(root))
print(root.PreorderTraversal(root))
print(root.PostorderTraversal(root))
output
Inorder traversal
[10, 14, 19, 27, 31, 42]
preorder traversal
[27, 14, 10, 19, 35, 42]
postorder traversal
[10, 19, 14, 31, 42, 27]
Result:
Thus the given program has been executed and verified successfully.
64
Ex.No: 10(a) BINARY SEARCH TREE
Date:
Aim:
Algorithm:
Program:
class Node:
65
while(current.left is not None):
current = current.left
return current
def deleteNode(root, key):
if root is None:
return root
if key < root.key:
root.left = deleteNode(root.left, key)
elif(key > root.key):
root.right = deleteNode(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 = minValueNode(root.right)
root.key = temp.key
root.right = deleteNode(root.right, temp.key)
return root
root = None
root = insert(root, 8)
root = insert(root, 3)
root = insert(root, 1)
root = insert(root, 6)
root = insert(root, 7)
root = insert(root, 10)
root = insert(root, 14)
root = insert(root, 4)
print("Inorder traversal: ", end=' ')
inorder(root)
print("\nDelete 4")
root = deleteNode(root, 4)
print("Inorder traversal: ", end=' ')
inorder(root)
print("\nDelete 6")
root = deleteNode(root, 6)
print("Inorder traversal: ", end=' ')
inorder(root)
print("\nDelete 3")
root = deleteNode(root, 3)
print("Inorder traversal: ", end=' ')
inorder(root)
66
Output:
Inorder traversal: 1-> 3-> 4-> 6-> 7-> 8-> 10-> 14->
Delete 4
Inorder traversal: 1-> 3-> 6-> 7-> 8-> 10-> 14->
Delete 6
Inorder traversal: 1-> 3-> 7-> 8-> 10-> 14->
Delete 3
Inorder traversal: 1-> 7-> 8-> 10-> 14->
67
Ex.No: 10(a) AVL TREE
Date:
Aim:
Algorithm:
Program:
import sys
class TreeNode(object):
def init (self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
class AVLTree(object):
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))
balanceFactor = self.getBalance(root)
if balanceFactor > 1:
if key < root.left.key:
68
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
def delete_node(self, root, key):
if not root:
return root
69
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
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
def getHeight(self, root):
if not root:
return 0
return root.height
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)
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 = [15,20,24,10,13,7,30,36,25]
for num in nums:
root = myTree.insert_node(root, num)
myTree.printHelper(root, "", True)
key = 24
root = myTree.delete_node(root, key)
70
print("After Deletion: ")
myTree.printHelper(root, "", True)
key = 20
root = myTree.delete_node(root, key)
R 13
L --- 10
| L --- 7
R 24
L --- 20
| L --- 15
R 30
L --- 25
R 36
After Deletion:
R 13
L --- 10
| L --- 7
R 25
L --- 20
| L --- 15
R 30
R --- 36
After Deletion:
R 13
L --- 10
| L --- 7
R 25
L --- 15
R 30
R --- 36
After Deletion:
R 13
L --- 10
| L --- 7
R 30
L --- 25
R 36
Result:
Thus the given program has been executed and verified successfully.
71
Ex.No: 10(a)
Date: MAX HEAP
Aim:
To write an program to implement max heap
Algorithm:
72
arr = []
insert(arr, 35)
insert(arr, 33)
insert(arr, 42)
insert(arr, 10)
insert(arr, 14)
insert(arr, 19)
insert(arr, 27)
insert(arr, 44)
insert(arr, 26)
print ("Max-Heap array: " + str(arr))
deleteNode(arr, 44)
print("After deleting an element: " + str(arr))
deleteNode(arr, 33)
print("After deleting an element: " + str(arr))
output:
Max-Heap array: [44, 42, 35, 33, 14, 19, 27, 10, 26]
After deleting an element: [42, 33, 35, 26, 14, 19, 27, 10]
After deleting an element: [42, 26, 35, 10, 14, 19, 27]
73
Ex.No: 11(b) MIN HEAP
Date:
Aim:
Algorithm:
Program:
def min_heapify(A,k):
l = left(k)
r = right(k)
if l < len(A) and A[l] < A[k]:
smallest = l
else:
smallest = k
if r < len(A) and A[r] < A[smallest]:
smallest = r
if smallest != k:
A[k], A[smallest] = A[smallest], A[k]
min_heapify(A, smallest)
def left(k):
return 2 * k + 1
def right(k):
return 2 * k + 2
def build_min_heap(A):
n = int((len(A)//2)-1)
for k in range(n, -1, -1):
min_heapify(A,k) A = [3,9,2,1,4,5]
build_min_heap(A)
print(A)
output:
Min heap:
[1, 3, 2, 9, 4, 5]
Result:
Thus the given program has been executed and verified successfully.
74
Ex.No: 12(a) GRAPH REPRESENTATION—ADJACENCY LIST
Date:
Aim:
To write a program to implement graph representation using Adjacency list
Algorithm:
Program:
class AdjNode:
75
output
76
Ex.No: 12(b)
GRAPH REPRESNTATION—ADJACENCY MATRIX
Date:
Aim:
To write a program to implement graph representation using Adjacency matrix
Algorithm:
Program:
class Graph:
n=0
g =[[0 for x in range(10)] for y in range(10)]
def init (self, x):
self. n = x
for i in range(0, self. n):
for j in range(0, self. n):
self. g[i][j]= 0
def displayAdjacencyMatrix(self):
print("\n\n Adjacency Matrix:", end ="")
for i in range(0, self. n):
print()
for j in range(0, self. n): print("", self. g[i][j], end ="")
def addEdge(self, x, y):
if(x>= self. n) or (y >= self. n):
print("Vertex does not exists !")
if(x == y):
print("Same Vertex !")
else:
self. g[y][x]= 1
self. g[x][y]= 1
def addVertex(self):
self. n = self. n + 1;
for i in range(0, self. n):
self. g[i][self. n-1]= 0
77
self. g[self. n-1][i]= 0
def removeVertex(self, x):
if(x>self. n):
print("Vertex not present !")
else:
while(x<self. n):
for i in range(0, self. n):
self. g[i][x]= self. g[i][x + 1]
for i in range(0, self. n):
self. g[x][i]= self. g[x + 1][i]
x=x+1
self. n = self. n - 1
obj = Graph(4);
obj.addEdge(0, 1);
obj.addEdge(0, 2);
obj.addEdge(1, 2);
obj.addEdge(2, 3);
obj.displayAdjacencyMatrix();
#obj.addVertex();
#obj.addEdge(4, 1);
#obj.addEdge(4, 3);
obj.displayAdjacencyMatrix();
obj.removeVertex(1);
obj.displayAdjacencyMatrix();
output
Adjacency Matrix:
0110
1010
1101
0010
Adjacency Matrix:
0110
1010
1101
0010
Adjacency Matrix:
010
101
010
78
Ex.No: 12(c) TRAVERSAL ALGORITHM—BFS
Date:
Aim:
To write a program to implement graph traversal algorithm using BFS
Algorithm:
1. Start by putting any one of the graph Vertices at the back of a queue.
2. Take the front item of the queue and add it to the visited list.
3. Create a list of that vertex’s adjacent nodes.Add the ones which aren’t in the visited list to the back of the queue.
4. Keep repeating steps 2 and 3 until the queue is empty
Program 1:
graph = {'5' : ['3','7'],'3' : ['2', '4'],'7' : ['8'],'2' : [],'4' : ['8'],'8' : []}
visited = []
queue = []
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')
output:
program 2:
graph = {'A': ['B', 'C', 'E'],'B': ['A','D', 'E'],'C': ['A', 'F', 'G'], 'D': ['B'],'E': ['A', 'B','D'], 'F': ['C'],'G': ['C']}
def bfs_connected_component(graph, start):
explored = []
queue = [start]
while queue:
node = queue.pop(0)
if node not in explored:
explored.append(node)
neighbours = graph[node]
for neighbour in neighbours:
queue.append(neighbour)
79
return explored
bfs_connected_component(graph,'A')
output:
['A', 'B', 'C', 'E', 'D', 'F', 'G']
80
Ex.No: 12(d) TRAVERSAL ALGORITHM—DFS
Date:
Aim:
To write a program to implement graph traversal algorithm using DFS
Algorithm:
1. Create a recursive function that takes the index of the node and a visited array.
2. Mark the current node as visited and print the node.
3. Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the
adjacent node.
4. Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS,
call the recursive function with the current node.
Program:
def recursive_dfs(graph, source,path = []):
if source not in path:
path.append(source)
if source not in graph:
return path
for neighbour in graph[source]:
path = recursive_dfs(graph, neighbour, path)
return path
graph = {"A":["B","C", "D"], "B":["E"],"C":["F","G"],"D":["H"],"E":["I"],"F":["J"]}
path = recursive_dfs(graph, "A")
print(" ".join(path))
output:
DFS
ABEICFJ GDH
Result:
Thus the given program has been executed and verified successfully.
81
Ex.No: 13 SINGLE SOURCE SHORTEST PATH ALGORITHM
Date:
Aim:
To write a program to implement single source shortest path algorithm
Algorithm:
1. Start with a weighted graph
2. Choose a starting vertex and assign infinity path values to all other vertices
3. Go to each vertex and update its path length
4. If the path length of the adjacent vertex is lesser than new path length, don’t update it
5. Avoid updating path length of already visited vertices
6. After each iteration pick the unvisited vertiex with the least path length
7. Repeat until all verties have been visited
Program:
import heapq
def calculate_distances(graph, starting_vertex):
distances = {vertex: float('infinity') for vertex in graph}
distances[starting_vertex] = 0
pq = [(0, starting_vertex)]
while len(pq) > 0:
current_distance, current_vertex = heapq.heappop(pq)
if current_distance > distances[current_vertex]:
continue
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances example_graph = {'v1': {'v2': 2, 'v4': 1,},'v2': {'v4': 3, 'v5': 10,},'v3': {'v1': 4,},'v4': {'v3': 2, 'v6': 8, 'v7': 4,
'v5': 2},'v5': {'v7': 6,},'v6': {'v3': 5,},'v7': {'v6': 1,},}
print(calculate_distances(example_graph, 'v1'))
output:
shortest path
{'v1': 0, 'v2': 2, 'v3': 3, 'v4': 1, 'v5': 3, 'v6': 6, 'v7': 5}
82
Ex.No: 14(a) KRUSKAL’S ALGORITHM
Date:
Aim:
Algorithm:
1. Sort all the edges in non-decreasing order of their weight.
2. Pick the smallest edge.
3. Check if it forms a cycle with the spanning tree formed so far.
4. If cycle is not formed, include this edge. Else, discard it.
5. 3. Repeat step2 until there are (V-1) edges in the spanning tree.
Program:
class Edge :
83
self.rank[root2] += 1
else :
self.parent[root2] = root1
self.rank[root1] += 1
print("\nEdges of minimum spanning tree in graph :", end=' ')
cost = 0
for edge in self.mst :
print("[" + str(edge.src) + "-" + str(edge.dst) + "](" + str(edge.weight) + ")", end = ' ')
cost += edge.weight
print("\nCost of minimum spanning tree : " +str(cost))
def main() :
num_nodes = 5
e1 = Edge(0, 1, 5)
e2 = Edge(0, 3, 6)
e3 = Edge(1, 2, 1)
e4 = Edge(1, 3, 3)
e5 = Edge(2, 3, 4)
e6 = Edge(2, 4, 6)
e7 = Edge(3, 4, 2)
g1 = Graph(num_nodes, [e1, e2, e3, e4, e5, e6, e7])
g1.KruskalMST()
if name == " main " :
main()
Output:
Edges of minimum spanning tree in graph : [1-2](1) [3-4](2) [1-3](3) [0-1](5) Cost of minimum spanning tree
: 11
84
Ex.No: 14(b) PRIM’S ALGORITHM
Date:
Aim:
Algorithm:
85
output:
Edge : Weight 0-
3:1
0-1:2
3-2:2
3-6:4
6-5:1
6-4:6
Result:
Thus the given program has been executed and verified successfully.
86