0% found this document useful (0 votes)
65 views59 pages

Lab Manual

The document outlines the academic structure and curriculum for the Data Structures and Algorithms Laboratory course at Jeppiaar Engineering College for the academic year 2023-24. It includes the college's vision and mission, program outcomes, educational objectives, specific outcomes, and course outcomes, along with a detailed list of experiments to be conducted. Additionally, the document provides examples of Python programs for implementing various data structures and algorithms.

Uploaded by

timmy345555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views59 pages

Lab Manual

The document outlines the academic structure and curriculum for the Data Structures and Algorithms Laboratory course at Jeppiaar Engineering College for the academic year 2023-24. It includes the college's vision and mission, program outcomes, educational objectives, specific outcomes, and course outcomes, along with a detailed list of experiments to be conducted. Additionally, the document provides examples of Python programs for implementing various data structures and algorithms.

Uploaded by

timmy345555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

JEPPIAAR NAGAR, RAJIV GANDHI SALAI

CHENNAI – 600119.

DEPARTMENT OF INFORMATION TECHNOLOGY

II YEAR B.TECH – III SEM

ACADEMIC YEAR 2023-24(ODD SEM)

Name :

Reg No :

Subject Name : DATA STRUCTURES AND ALGORITHMS LABORATORY

Subject Code : CD3281

Batch : 2022-2026

1
JEPPIAAR NAGAR, RAJIVGANDHI SALAI

CHENNAI – 600119.

DEPARTMENT OF INFORMATION TECHNOLOGY

This is a Bonafide Record Work of

Register No. submitted for the Anna University

Practical Examination held on in CD3281 DATA STRUCTURES AND

ALGORITHMS LABORATORY during the year .

Signature of the Lab-In-Charge Signature of the HOD

Date:

Examiners:

Internal:

External:

2
COLLEGE VISION & MISSION
Vision
To build Jeppiaar Engineering College as an Institution of Academic Excellence in Technical
education and Management education and to become a World Class University.
Mission

M1 To excel in teaching and learning, research and innovation by promoting the


principles of scientific analysis and creative thinking

To participate in the production, development and dissemination of knowledge and


M2
interact with national and international communities

To equip students with values, ethics and life skills needed to enrich their lives and
M3
enable them to meaningfully contribute to the progress of society

M4 To prepare students for higher studies and lifelong learning, enrich them with the
practical and entrepreneurial skills necessary to excel as future professionals and
contribute to Nation’s economy

Program Outcomes (POs)


Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
PO1 an engineering specialization to the solution of complex engineering problems.
Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
PO2 problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems and design
PO3 system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations
Conduct investigations of complex problems: Use research-based knowledge and research methods
PO4 including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
PO6 health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
Environment and sustainability: Understand the impact of the professional engineering solutions in
PO7 societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
PO8 engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader in diverse
PO9 teams, and in multidisciplinary settings.

Communication: Communicate effectively on complex engineering activities with the engineering


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

3
DEPARTMENT OF INFORMATION TECHNOLOGY
Vision
To produce engineers with excellent knowledge in the field of Information Technology
through scientific and practical education to succeed in an increasingly complex world.
Mission
To demonstrate technical and operational excellence through creative and critical
M1
thinking for the effective use of emerging technologies.
To involve in a constructive, team oriented environment and transfer knowledge to
M2
enable global interaction.
M3 To enrich students with professional integrity and ethical standards that will make
them deal social challenges successfully in their life.
To devise students for higher studies and perpetual learning, upgrade them as
M4
competent engineers and entrepreneurs for country’s development.

Program Educational Objectives (PEOs)


PEO1 To support students with substantial knowledge for developing and resolving
mathematical, scientific and engineering problems
PEO2 To provide students with adequate training and opportunities to work as a collaborator
with informative and administrative qualities
PEO3 To shape students with principled values to follow the code of ethics in social and
professional life
PEO4 To motivate students for extensive learning to prepare them for graduate studies, R&D
and competitive exams
PEO5 To cater the students with industrial exposure in an endeavor to succeed in the emerging
cutting edge technologies

Program Specific Outcomes (PSOs)


Students will be able to

Students are able to analyze, design, implement and test any software with the programming
PSO1 and testing skills they have acquired.

Students are able to design algorithms, data management to meet desired needs, for real time
PSO2 problems through analytical, logical and problem solving skills.
Students are able to provide security solutions for network components and data storage &
PSO3 management which will enable them to work in the industry ethically.

Course Outcomes (COs)


C206.1 Implement ADTs as Python classes

Design, implement, and analyse linear data structures, such as lists, queues, and stacks,
C206.2 according to the needs of different applications
C206.3 Design and Implement Hashing techniques.
Design, implement, and analyse efficient tree structures to meet requirements such as
C206.4 searching, indexing, and sorting

4
Model problems as graph problems and implement efficient graph algorithms to solve
C206.5 them

5
LIST OF EXPERIMENTS

1. Implement simple ADTs as Python classes


2. Implement recursive algorithms in Python
3. Implement List ADT using Python arrays
4. Linked list implementations of List
5. Implementation of Stack and Queue ADTs
6. Applications of List, Stack and Queue ADTs
7. Implementation of sorting and searching algorithms
8. Implementation of Hash tables
9. Tree representation and traversal algorithms
10. Implementation of Binary Search Trees
11. Implementation of Heaps
12. Graph representation and Traversal algorithms
13. Implementation of single source shortest path algorithm
14. Implementation of minimum spanning tree algorithms

6
INDEX PAGE
DATE OF THE DATE OF MARKS SIGNATURE
S.NO NAME OF THE EXPERIMENT Page No
EXPERIMENT SUBMISSION (25) WITH DATE
Implement simple ADTs as Python
1 classes
Implement recursive algorithms in
2 Python
Implement List ADT using Python
3 arrays
Implementation of Singly Linked
4 List
Implementation of Stack using list
5 Implementation of Linear Queue
using list
Applications of List, Stack and
6 Queue ADTs
7a Implementation of Bubble sort
7b Implementation of Insertion Sort
7c Implementation of Selection Sort
7d Implementation of Merge Sort
7e Implementation of Quick Sort

8a Implementation of Linear search


8b Implementation of Binary search
9 Implementation of Hash tables

Tree representation and traversal


10 algorithms

Implementation of Binary Search


11 Trees
12a Implementation of Max Heap
12b Implementation of Min Heap
Graph Representation Using
Adjacency List
Graph Representation Using
Adjacency Matrix
Graph Traversal Algorithm Using
13 BFS

Graph Traversal Algorithm Using


DFS

7
Implementation of single source
shortest path algorithm
14

Assessment
Implementation of Singly Linked
List
Implementation of Binary search
Tree representation and traversal
Algorithms
Content Beyond Syllabus
Implementation of minimum spanning tree
15 algorithms- Kruskal’s algorithm
Implementation of minimum spanning tree
16 algorithms-Prim’s algorithm
Program Completion (25)

Assessment marks (15)

TOTAL MARKS (40)

8
Ex No:1
Date : Implement simple ADTs as Python classes

AIM:

To write the Python program to implement simple ADTs as Python


Classes.
ALGORITHM:
Step 1: Start
Step 2: Declare Variable n, fact, i
Step 3: Read number from User
Step 4: Initialize Variable fact=1 and i=1
Step 5: Repeat Until i<=number
Step 6: Print fact

PROGRAM:
class factorial:
def findFact(self, n):
f=1
for i in range(1, n + 1):
f=f*i
return f

print("Enter a Number: ", end="")


num = int(input())

ob = factorial()
print("\nFactorial of", num, "=", ob.findFact(num))

OUTPUT :
Enter a Number: 6

Factorial of 6 = 720

RESULT :

Thus the python program for implementing simple ADTs as Python


classes has been executed and the output is verified successfully

9
Ex No:2
Date : Implement recursive algorithms in Python

AIM:
To write the Python program to implement recursive algorithms in
Python
ALGORITHM:
1. Create n variables and initialize them
2. Create another variable to keep track of the length of the Fibonacci
sequence to be printed (length)
3. Loop (length is less than series length)
4. Print first + second
5. Update n variables
PROGRAM:
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms =int(input("Enter the no of terms "))
# check if the number of terms is valid
if n_terms <= 0:
print("Invalid input ! Please input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))

OUTPUT:
Enter the no of terms 6
Fibonacci series:
0
1
1
2
3
5

RESULT :
Thus the python program for implementing has been executed and the
output is verified successfully.

10
Ex No:3
Date : Implement List ADT using Python arrays

AIM:

To write the Python program to implement List ADT using Python arrays
ALGORITHM:
Step 1: Creating a List with the use of multiple values
Step 2: Accessing a element from the list using index number
Step 3: Accessing a element
Step 4: Print the last element of list
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, ")
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)

11
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


2.Display Student Details
3.Search Details of a Student
4.Delete Details of Student
5.Update Student Details
6.Exit

List of Students

Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100

Name : B
RollNo : 2
Marks1 : 90
Marks2 : 90

Name : C

12
RollNo : 3
Marks1 : 80
Marks2 : 80

Student Found,
Name : B
RollNo : 2
Marks1 : 90
Marks2 : 90

2
List after deletion
Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100

Name : C
RollNo : 3
Marks1 : 80
Marks2 : 80

2
List after updation
Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100

Name : C
RollNo : 2
Marks1 : 80
Marks2 : 8

RESULT :

Thus the python program for implementing List ADT using Python
arrays has been executed and the output is verified successfully.

13
Ex No:4
Date : Implementation of Singly Linked List

AIM:

To write the Python program to implement Singly Linked List


ALGORITHM:
Step 1 : Include all the header files which are used in the program.
Step 2 : Declare all the user defined functions.
Step 3 : Define a Node structure with two members data and next
Step 4 : Define a Node pointer 'head' and set it to NULL.
Step 5: Implement the main method by displaying operations menu and make
suitable function calls in the main method to perform user selected operation.
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
self.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:
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:
14
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")
print ("Count of nodes is :",list.getCount())
list.RemoveNode("2")
list.listprint()

15
OUTPUT :
Item found
Count of nodes is : 6
4
1
6
2
3
5

after removing
4
1
6
3
5

RESULT :

Thus the python program for implementation of Singly Linked List


has been executed and the output is verified successfully.

16
Ex No:5(a)
Date : Implementation of Stack using list

AIM:

To write Python program to Implementation of Stack using Linked List.


ALGORITHM:

1. PUSH() Operation:
Step 1: Start
Step 2: Create a node new and declare variable top
Step 3: Set new data part to be Null // The first node is created, having null
value and top pointing to it
Step 4: Read the node to be inserted.
Step 5: Check if the node is Null, then print "Insufficient Memory"
Step 6: If node is not Null, assign the item to data part of new and assign top to
link part of new and also point stack head to new.
2. POP() Operation:
Step 1: Start
Step 2: Check if the top is Null, then print "Stack Underflow."
Step 3: If top is not Null, assign the top's link part to ptr and assign ptr to
stack_head's link part.
Step 4: Stop
3. PEEK() Operation:
Step 1: Start
Step 2: Print or store the node pointed by top variable
Step 3: Stop
PROGRAM:

class Node:
def init (self,data): self.data=data self.next=None
class Stack:
def init (self):
self.head=None
self.ctr=0
self.top=None
def Push(self,data):
node=Node(data)
if self.head==None:
self.head=node
self.top=node
else:
self.top.next=node
self.top=node

print("Node pushed to stack",data)


17
self.ctr+=1
return
def Pop(self):
if self.head==None:
print("Stack Underflow")
elif self.head==self.top:
print("Deleted from Stack",self.head.data)
self.head=self.top=None
self.ctr-=1
else:
print("Deleted from Stack",self.top.data)
temp=self.head
while temp.next is not self.top:
temp=temp.next
temp.next=None
self.top=temp
self.ctr-=1
return

def Traverse(self):
if self.head==None:
print("No Nodes exist")
return
temp=self.head
while temp is not None:
print(temp.data)
temp=temp.next
def Menu():

print("1.Push\n2.Pop\n3.Traverse\n4.Number of nodes\n5.Exit")
ch=int(input("Enter choice:"))
return ch
s=Stack()
print("**************Stack*****************")
while True:
ch=Menu()
if ch==1:
data=input("Enter data:")
s.Push(data)
elif ch==2:
s.Pop()
elif ch==3:
s.Traverse()
elif ch==4:
print("Number of nodes",s.ctr)
else:
18
print('Quit')
break

19
OUTPUT :

RESULT :

Thus the python program for Implementation of Stack using Linked List
has been executed and the output is verified successfully.

20
Ex No:5(b)
Date : Implementation of Linear Queue using list

AIM:

To write the Python program to implement Linear Queue using list


ALGORITHM:
Step 1: Include all the header files which are used in the program. And declare
all the user
defined functions.
Step 2 : Define a 'Node' structure with two members data and next.
Step 3: Define two Node pointers 'front' and 'rear' and set both to NULL.
Step 4 : Implement the main method by displaying Menu of list of operations
and make suitable function calls in the main method to perform user selected
operation.

enQueue(value) - Inserting an element into the Queue


Step 1: Create a newNode with given value and set 'newNode → next' to
NULL.
Step 2: Check whether queue is Empty (rear == NULL)
Step 3: If it is Empty then, set front = newNode and rear = newNode.
Step 4 - If it is Not Empty then, set rear → next = newNode and rear =
newNode.

deQueue() - Deleting an Element from Queue


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

display() - Displaying the elements of Queue


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

PROGRAM:
front=0
rear=0
mymax=eval(input("Enter maximum size of queue:"))

21
def createQueue():
queue=[]
return queue
def isEmpty(queue):
return len(queue)==0
def enqueue(queue,item):
queue.append(item)
print("Enqueued to queue",item)
def dequeue(queue):
if isEmpty(queue):
return "Queue is empty"
item=queue[0]
del queue[0]
return item
queue=createQueue()
while True:
print("1.Enqueue")
print("2.Dequeue")
print("3.Display")
print("4.Quit")
ch=int(input("Enter your choice"))
if ch==1:
if rear<mymax:
item=input("Enter any elements:")
enqueue(queue,item)
rear+=1
else:
print("Queue is full")
elif ch==2:
print(dequeue(queue))
elif ch==3:
print(queue)
else:
print("Exit")
break

OUTPUT :
Enter maximum size of queue:5
1.Enqueue
2.Dequeue
3.Display
4.Quit
Enter your choice1
Enter any elements:3
Enqueued to queue 3
22
1.Enqueue
2.Dequeue
3.Display
4.Quit
Enter your choice1
Enter any elements:6
Enqueued to queue 6
1.Enqueue
2.Dequeue
3.Display
4.Quit
Enter your choice2
3
1.Enqueue
2.Dequeue
3.Display
4.Quit
Enter your choice3
['6']
1. Enqueue
2.Dequeue
3.Display
4.Quit
Enter your choice

RESULT :

Thus the python program for implementing Linear Queue using list has
been executed and the output is verified successfully.

23
Ex No:6
Date : Applications of List, Stack and Queue ADTs

AIM:

To write the Python program to implement the Applications of List, Stack


and Queue ADTs
ALGORITHM:
Step 1: Create a class Node with instance variables data and next.
Step 2: Create a class Stack with instance variable head.
Step 3: The variable head points to the first element in the linked list.
Step 4: Define methods push and pop inside the class Stack.
Step 5: The method push adds a node at the front of the linked list.
Step 6: The method pop 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.
Application of queue using list:
Step 1: Create a class Node with instance variables data and next.
Step 2: Create a class Queue with instance variables head and last.
Step 3: The variable head points to the first element in the linked list while last
points to the last element.
Step 4: Define methods enqueue and dequeue inside the class Queue.
Step 5: The method enqueue adds a node at the end of the linked list.
Step 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.
Step 7: Create an instance of Queue and present a menu to the user to perform
operations on the queue.
PROGRAM:
front=0
rear=0
mymax=eval(input("Enter maximum size of queue:"))
def createQueue():
queue=[]
return queue
def isEmpty(queue):
return len(queue)==0
def enqueue(queue,item):
queue.append(item)
print("Enqueued to queue",item)
def dequeue(queue):
if isEmpty(queue):
return "Queue is empty"
item=queue[0]
del queue[0]
return item
queue=createQueue()
24
while True:
print("1.Enqueue")
print("2.Dequeue")
print("3.Display")
print("4.Quit")
ch=int(input("Enter your choice:"))
if ch==1:
if rear<mymax:
item=input("Enter any elements:")
enqueue(queue,item)
rear+=1
else:
print("Queue is full")
elif ch==2:
print(dequeue(queue))
elif ch==3:
print(queue)
else:
print("Exit")
break

OUTPUT :

RESULT :

Thus the python program has been executed and the output is verified
successfully.

25
Ex No:7(a)
Date : Implementation of Bubble sort

AIM:
To write the Python program to implement Bubble sort
ALGORITHM:
Step 1: Optimize code, so if the array is already sorted, it doesn't need to go
through the entire process.
Step 2: Traverse through all array elements range (n) also work but outer loop will
Step 3: Repeat one time more than needed
Step 4: Last i elements are already in place
PROGRAM:
def bubble_sort(a):
n = len(a)
for i in range(n):
for j in range(0, n-i-1):
if a[j] > a[j+1] :
a[j], a[j+1] = a[j+1], a[j]
print("Enter elements into list:")
a=[int(x) for x in input().split()]
bubble_sort(a)
print("The sorted list is ",a)

OUTPUT :
Enter elements into list:
47914 2
The sorted list is [1, 2, 4, 7, 9]

RESULT :
Thus the python program for implementing Bubble sort has been
executed and the output is verified successfully.

26
Ex No:7(b)
Date : Implementation of Insertion Sort

AIM:

To write the Python program to implement Insertion Sort


ALGORITHM:
1. Iterate over the input elements by growing the sorted array at each
iteration.
2. Compare the current element with the largest value available in the
sorted array.
3. If the current element is greater, then it leaves the element in its place
and moves on to the next element else it finds its correct position in the
sorted array and moves it to that position
4. This is achieved by shifting all the elements towards the right, which
are larger than the current element, in the sorted array to one position
ahead.
PROGRAM:
def insertion_sort(a):
for i in range(1,len(a)):
temp=a[i]
pos=i
while pos>0 and a[pos-1]>temp:
a[pos]=a[pos-1]
pos-=1
a[pos]=temp
print("Enter elements into list:")
a=[int(x) for x in input().split()]
insertion_sort(a)
print("The sorted list is",a)

OUTPUT :
Enter elements into list:
2719
The sorted list is [1, 2, 7, 9]

RESULT :

Thus the python program for implementing Insertion Sort has been
executed and the output is verified successfully.

27
Ex No:7(c)
Date : Implementation of Selection Sort

AIM:
To write the Python program to implement Selection Sort
ALGORITHM:
Step 1: Selection sort in Python
Step 2: Time complexity O(n*n)
Step 3: Sorting by finding min_index
Step 4: Select the minimum element in every iteration
Step 5: Swapping the elements to sort the array
PROGRAM:
arr = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):
arr.append(int(input("Enter the element:")))
print ("The array is:",arr)
for i in range(0,n):
j=i+1
for j in range(j, n):
if arr[i] > arr[j]:
arr[i] ,arr[j] =arr[j] ,arr[i]
print ("Sorted array is:",arr)

OUTPUT :
Enter the Size of the List:5
Enter the element:45
Enter the element:7
Enter the element:28
Enter the element:65
Enter the element:3
The array is: [45, 7, 28, 65, 3]
Sorted array is: [3, 7, 28, 45, 65]

RESULT :

Thus the python program for implementing Selection Sort has been
executed and the output is verified successfully.

28
Ex No:7(d)
Date : Implementation of Merge Sort

AIM:

To write the Python program to implement of Merge Sort


ALGORITHM:
Step1: Merges two subarrays of arr[].
Step2: First subarray is arr[l..m]
Step3: Second subarray is arr[m+1..r]
Step4: Create temp arrays
Step5: Copy data to temp arrays L[] and R[]
Step6: Merge the temp arrays back into arr[l..n]
Step7: Copy the remaining elements of L[]
Step8: l is for left index and r is right index of the sub-array of arr to be
sorted
Step9: Same as (l+r)//2, but avoids overflow for large l and h
Step10: Sort first and second halves
PROGRAM:
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i=0
j=0
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

29
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
arr = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):
arr.append(int(input("Enter the element:")))
print ("The array is:",arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)

OUTPUT :

Enter the Size of the List:7


Enter the element:54
Enter the element:5
Enter the element:41
Enter the element:12
Enter the element:17
Enter the element:65
Enter the element:7
The array is: [54, 5, 41, 12, 17, 65, 7]
Sorted array is:
5 7 12 17 41 54 65

RESULT :

Thus the python program for implementing Merge Sort has been
executed and the output is verified successfully.
30
Ex No:7(e)
Date : Implementation of Quick Sort

AIM:
To write the Python program to implement Quick Sort
ALGORITHM:
1. Pick an element, called a pivot, from the array.
2. Partitioning: reorder the array so that all elements with values less
than the pivot come before the pivot, while all elements with values
greater than the pivot come after it (equal values can go either way).
After this partitioning, the pivot is in its final position. This is called
the partition operation.
3. Recursively apply the above steps to the sub-array of elements with
smaller values and separately to the sub-array of elements with
greater values.

PROGRAM:
import random
def pivot_place(list1,first,last):
rindex = random.randint(first, last)
list1[rindex], list1[last] = list1[last], list1[rindex]
pivot = list1[last]
left = first
right = last-1
while True:
while left <= right and list1[left] <= pivot:
left = left+1
while left <= right and list1[right] >= pivot:
right = right-1
if right < left:
break
else:
list1[left], list1[right] = list1[right], list1[left]
list1[last], list1[left] = list1[left], list1[last]
return left
def quicksort(list1, first, last):
if first < last:
p=pivot_place(list1, first, last)
quicksort(list1, first, p-1)
quicksort(list1, p+1, last)
list1 = list()
n=int(input("Enter the Size of the List:"))

31
for i in range(n):
list1.append(int(input("Enter the element:")))
print ("The array is:",list1)
quicksort(list1, 0, n-1)
print(list1)

OUTPUT :
Enter the Size of the List:5
Enter the element:45
Enter the element:6
Enter the element:25
Enter the element:64
Enter the element:2
The array is: [45, 6, 25, 64, 2]
The sorted array is: [2, 6, 25, 45, 64]

RESULT :

Thus the python program for implementing quick sort has been
executed and the output is verified successfully.

32
Ex No:8(a)
Date : Implementation of Linear search

AIM:
To write the Python program to implement Linear search
ALGORITHM:
 Start from the leftmost element of arr[] and one by one compare x
with each element of arr[]
 If x matches with an element, return the index.
 If x doesn’t match with any of the elements, return -1.

PROGRAM:
print("Enter the list")
a = [int(x) for x in input().split()]
print (a)
search = int(input("Enter search number"))
for i in range(0,len(a)):
if (search==a[i]):
print(str(search) + " found at position " +str(i))
if(search!=a[i]):
print(" element not found at any position ")

OUTPUT :
586
[5, 8, 6]
Enter search number2
element not found at any position

RESULT :

Thus the python program for Linear search has been executed and the
output is verified successfully.

33
Ex No:8(b)
Date : Implementation of Binary search

AIM:
To write the Python program to implement Binary search
ALGORITHM:
1. Create a function binary_search () which accepts 4 parameters (array,
low, high, a).
2. Then Follow step 3 until the lowest and highest meet each other:
3. mid = (low + high) / 2 if a == arr [mid] return mid ...
4. Intialize the array and the element to be found
5. Print the resulting position if the element is found else print Not
found.
PROGRAM:
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
n=int(input("Enter the Size of the List:"))
arr= [int(x) for x in input().split()]
print ("The array is:",arr)
x=int(input("Enter the element to be search:"))
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")

OUTPUT :
Enter the Size of the List:7
1 5 7 8 9 11 12
The array is: [1, 5, 7, 8, 9, 11, 12]
Enter the element to be search:7
Element is present at index 2
RESULT :

Thus the python program for Binary search has been executed and the
output is verified successfully.

34
Ex No:9
Date : Implementation of Hash tables

AIM:
To write the Python program to implement Hash tables
ALGORITHM:
Step 1: Creating Hashtable as a nested list.
Step 2: Hashing Function to return key for every value.
Step 3: Insert Function to add values to the hash table
Step 4: Display_hash
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)
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

35
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))
table1 = hashTable()
table1.insert(50)
table1.insert(100)
table1.insert(76)
table1.insert(85)
36
table1.insert(92)
table1.insert(73)
table1.insert(101)
table1.display()
print()
print("The position of element 92 is : " + str(table1.search(92)))
print("The position of element 85 is : " + str(table1.search(85)))
print("\nTotal number of comaprisons done for searching = " +
str(table1.comparisons))
print()
table1.remove(73)
table1.display()

OUTPUT :
Enter the Size of the hash table : 7
Element 50 at position 1
Element 100 at position 2
Element 76 at position 6
Collision has occured for element 85 at position 1 finding new Position.
Collision has occured for element 92 at position 1 finding new Position.
Collision has occured for element 73 at position 3 finding new Position.
Collision has occured for element 101 at position 3 finding new Position.
0 = 101
1 = 50
2 = 100
3 = 85
4 = 92
5 = 73
6 = 76
The number of element is the Table are : 7
The position of element 92 is : 4
The position of element 85 is : 3
Total number of comaprisons done for searching = 7
Element 73 is Deleted
0 = 101
1 = 50
2 = 100
3 = 85
4 = 92
5=0
6 = 76
The number of element is the Table are : 6

RESULT :

Thus the python program for implementation of Hash tables has been
executed and the output is verified successfully.
37
Ex No:10
Date : Tree representation and traversal algorithms

AIM:
To write the Python program to implement Tree representation algorithm
ALGORITHM:
Step 1: In-order Traversal In this traversal method, the left subtree is
visited first, then the root and later the right sub-tree. ...
Step 2: Pre-order Traversal In this traversal method, the root node is
visited first, then the left subtree and finally the right subtree. ...
Step 3: Post-order Traversal In this traversal method, the root node is
visited last
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:
res = self.inorderTraversal(root.left)
res.append(root.data)
res = res + self.inorderTraversal(root.right)
return res
38
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, 35, 42]


Preorder Traversal: [27, 14, 10, 19, 35, 31, 42]
Postorder Traversal: [10, 19, 14, 31, 42, 35, 27]

RESULT :

Thus the python program for implementation of Tree representation


algorithm has been executed and the output is verified successfully.

39
Ex No:11
Date : Implementation of Binary Search Trees

AIM:
To write the Python program to implement of Binary Search Tree
ALGORITHM:
Step 1: We need to create a class (Binary Tree) with instance variable keys, left
and right.
Step 2: Then we define methods set_root, insert_left, insert_right, inorder, and
search.
Step 3: The set_root method will take the key as an argument and set the
variable key equal to it.
Step 4: The insert_left and insert_right methods will insert a node as a left and
right child, respectively.
Step 5: The inorder method displays the inorder traversal.
Step 6: The method search returns a node with a specified key.
Step 7: We need to define the count_nodes function, which will take a binary
tree as an argument.
Step 8: The recursive function count_nodes returns the number of nodes in the
binary tree.

PROGRAM:
class Node:
def init (self, key):
self.key = key
self.left = None
self.right = None
def inorder(root):
if root is not None:
inorder(root.left)
print(str(root.key) + "->", end=' ')
inorder(root.right)
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
else:
node.right = insert(node.right, key)
return node
def minValueNode(node):
current = node
while(current.left is not None):
current = current.left
return current
def deleteNode(root, key):

40
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)

41
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->

RESULT :

Thus the python program for implementation of Binary Search Tree has
been executed and the output is verified successfully

42
Ex No:12(a)
Date : Implementation of Max Heap

AIM:
To write the Python program to implement MAX HEAP
ALGORITHM:
Step1: The Heap Sort Algorithm in Python, is divided amongst two functions.
Step2: One of them is responsible for creating the heap,
Step3: and the other is responsible for the swapping of elements within the heap
to build a max heap.
Step4: Left child node of a node, multiply the index position by 2 and add 1.
This is shown in the code as 2 * i + 1.
Step5: For the right child node, you do 2 * i + 2.
Step16: The second for loop in it, does something similar, but swaps the root
node with the last value.
PROGRAM:
def heapify(arr, n, i):
largest = i
l=2*i+1
r=2*i+2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr, n, largest)
def insert(array, newNum):
size = len(array)
if size == 0:
array.append(newNum)
else:
array.append(newNum);
for i in range((size//2)-1, -1, -1):
heapify(array, size, i)
def deleteNode(array, num):
size = len(array)
i=0
for i in range(0, size):
if num == array[i]:
break
array[i], array[size-1] = array[size-1], array[i]
array.remove(num)
for i in range((len(array)//2)-1, -1, -1):
heapify(array, len(array), i)
arr = []
insert(arr, 35)
43
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]

RESULT :

Thus the python program for implementation of MAX HEAP has been
executed and the output is verified successfully

44
Date : Implementation of Min Heap

AIM:

To write the Python program to implement Min heap


ALGORITHM:
1. Build a min heap from the input data.
2. At this point, the smallest item is stored at the root of the heap.
Replace it with the last item of the heap followed by reducing the size
of heap by 1. Finally, heapify the root of tree.
3. Repeat above steps while size of heap is greater than 1.

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 python program for implementation of Min heap has been
executed and the output is verified successfully.

45
Ex No:13(a)
Date : Graph Representation Using Adjacency List

AIM:

To write the Python program to implement Graph Representation Using


Adjacency List
ALGORITHM:
 Centrality between the two: It is not only the users who have the most
friends that are important,
 the users who connect one geography to another are also important
because
 The centrality of the in-between quantifies the number of times a
particular node arrives in the shortest path chosen between two other
nodes.
 Degree of centrality: this is simply the number of connections for a node.
PROGRAM:
class AdjNode:
def init (self, data):
self.vertex = data
self.next = None
class Graph:
def init (self, vertices):
self.V = vertices
self.graph = [None] * self.V
def add_edge(self, src, dest):
node = AdjNode(dest)
node.next = self.graph[src]
self.graph[src] = node
node = AdjNode(src)
node.next = self.graph[dest]
self.graph[dest] = node
def print_graph(self):
for i in range(self.V):
print("Adjacency list of vertex {}\n head".format(i), end="")
temp = self.graph[i]
while temp:
print(" -> {}".format(temp.vertex), end="")
temp = temp.next
print(" \n")
if __name == " main ":
V=5
graph = Graph(V)
graph.add_edge(0, 1)

46
graph.add_edge(0, 4)
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(1, 4)
graph.add_edge(2, 3)
graph.add_edge(3, 4)
graph.print_graph()

OUTPUT :

Adjacency list of vertex 0


head -> 4 -> 1

Adjacency list of vertex 1


head -> 4 -> 3 -> 2 -> 0

Adjacency list of vertex 2


head -> 3 -> 1

Adjacency list of vertex 3


head -> 4 -> 2 -> 1

Adjacency list of vertex 4


head -> 3 -> 1 -> 0

RESULT :

Thus the python program for implementation of Graph Representation


Using Adjacency List has been executed and the output is verified successfully

47
Date : Graph Representation Using Adjacency Matrix

AIM:

To write the Python program to implement Graph Representation Using


Adjacency Matrix
ALGORITHM:
 Firstly, create an Empty Matrix
 Look in the graph and staring filling the matrix from node
 Replace all the 0 values with NULL.After completely filling the blocks
Matrix
 Finally Matrix is Ready
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
self. g[self. n-1][i]= 0
def removeVertex(self, x):
if(x>self. n):
print("Vertex not present !")
else:
48
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

RESULT :

Thus the python program for implementation of Graph Representation


Using Adjacency matrix has been executed and the output is verified
successfully

49
Ex No:13(c)
Date : Graph Traversal Algorithm Using BFS

AIM:
To write the Python program to implement Graph Traversal Algorithm
Using BFS
ALGORITHM:
Step 1: Start at the root node and push it onto the stack. Check for any adjacent
nodes of the tree and select one node.
Step 2: Raverse the entire branch of the selected node and push all the nodes
into the stack.
Step 3: Upon reaching the end of a branch (no more adjacent nodes) i.e nth leaf
node, move back by a single step and look for adjacent nodes of the n-1th node.
Step 4: If there are adjacent nodes for the n-1th node, traverse those branches
and push nodes onto the stack.
PROGRAM:
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
bfs(visited, graph, 'A')
OUTPUT :
AB C D E F
RESULT :

Thus the python program has been executed and the output is
verified successfully

50
Date : Graph Traversal Algorithm Using DFS

AIM:

To write the Python program to implement Graph Traversal Algorithm


Using DFS
ALGORITHM:
Step 1: SET STATUS = 1 (ready state) for each node in G
Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting
state)
Step 3: Repeat Steps 4 and 5 until STACK is empty
Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)
Step 5: Push on the stack all the neighbors of N that are in the ready state
(whose STATUS= 1) and set their STATUS = 2 (waiting state)
[END OF LOOP]
Step 6: EXIT
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
AB EI CF JG D H

RESULT :

Thus the python program for implementation of Graph Traversal


algorithm Using DFS has been executed and the output is verified successfully

51
Ex No:14
Date : Implementation of single source shortest path
algorithm
AIM:
To write the Python program to implement single source shortest path
algorithm
ALGORITHM:
1. Create an array d[] to store the shortest distance of all vertex from
the source vertex. Initialize this array by infinity except for d[S] = 0
where S is the source vertex.
2. Create a queue Q and push starting source vertex in it.
 while Queue is not empty, do the following for each
edge(u, v) in the graph
 If d[v] > d[u] + weight of edge(u, v)
 d[v] = d[u] + weight of edge(u, v)
 If vertex v is not present in Queue, then push the vertex v
into the Queue.
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'))

52
OUTPUT :
shortest path
{'v1': 0, 'v2': 2, 'v3': 3, 'v4': 1, 'v5': 3, 'v6': 6, 'v7': 5}

RESULT :

Thus the python program for implementation of single source shortest


path algorithm has been executed and the output is verified successfully

53
Ex No:15(a)
Date : Implementation of minimum spanning tree algorithms
- Kruskal’s algorithm

AIM:

To write the Python program to implement


ALGORITHM:
 Sort all the edges of the graph in ascending order of their weights.
 Check the edge with minimum weight, if including it in the answer
forms a cycle discard it, otherwise include it in the answer.
 Repeat the above step until we have chosen V-1 V − 1 edges.

PROGRAM:
class Edge :

def init (self, arg_src, arg_dst, arg_weight) :


self.src = arg_src
self.dst = arg_dst
self.weight = arg_weight
class Graph :
def init (self, arg_num_nodes, arg_edgelist) :
self.num_nodes = arg_num_nodes
self.edgelist = arg_edgelist
self.parent = []
self.rank = []
self.mst = []
def FindParent (self, node) :
if node != self.parent[node] :
self.parent[node] = self.FindParent(self.parent[node])
return self.parent[node]
def KruskalMST (self) :
self.edgelist.sort(key = lambda Edge : Edge.weight)
self.parent = [None] * self.num_nodes
self.rank = [None] * self.num_nodes
for n in range(self.num_nodes) :
self.parent[n] = n
self.rank[n] = 0
for edge in self.edgelist :
root1 = self.FindParent(edge.src)
root2 = self.FindParent(edge.dst)
if root1 != root2 :
self.mst.append(edge)
if self.rank[root1] < self.rank[root2] :
self.parent[root1] = root2
self.rank[root2] += 1
54
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

RESULT :
Thus the python program for implementation of Kruskal’s algorithm has
been executed and the output is verified successfully

55
Ex No:15(b)
Date : Implementation of minimum spanning tree algorithms
- Prim’s algorithm

AIM:

To write the Python program to implement minimum spanning tree


algorithms- Prim’s algorithm

ALGORITHM:
Step 1 - Remove all loops and parallel edges
Step 2 - Choose any arbitrary node as root node
Step 3 - Check outgoing edges and select the one with less cost

PROGRAM:

INF = 9999999
V=7
G = [[0, 2, 4, 1, 0, 0, 0],
[2, 0, 0, 3, 7, 0, 0],
[4, 0, 0, 2, 0, 5, 0],
[1, 3, 2, 0, 7, 8, 4],
[0, 7, 0, 7, 0, 0, 6],
[0, 0, 5, 8, 0, 0, 1],
[0, 0, 0, 4, 6, 1, 0]]
selected = [0, 0, 0, 0, 0, 0, 0]
no_edge = 0
selected[0] = True
print("Edge : Weight\n")
while (no_edge < V - 1):
minimum = INF
x=0
y=0
for i in range(V):
if selected[i]:
for j in range(V):
if ((not selected[j]) and G[i][j]):
if minimum > G[i][j]:
minimum = G[i][j]
x=i
y=j
print(str(x) + "-" + str(y) + ":" + str(G[x][y]))
selected[y] = True
no_edge += 1

56
OUTPUT :
Edge : Weight
0-3:1
0-1:2
3-2:2
3-6:4
6-5:1
6-4:6

RESULT :

Thus the python program for implementation of Prim’s algorithm


has been executed and the output is verified successfully.

57
59

You might also like