0% found this document useful (0 votes)
11 views51 pages

DSD Lab Manual

The document is a lab manual for the Data Structures Design Laboratory course at M.A.M. School of Engineering, detailing objectives, experiments, and outcomes for students. It includes a syllabus with various programming tasks in Python, such as implementing ADTs, sorting algorithms, and data structures like stacks, queues, trees, and graphs. The manual is aimed at helping students develop practical skills in data structure design and implementation.

Uploaded by

Iniyavanibtech
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)
11 views51 pages

DSD Lab Manual

The document is a lab manual for the Data Structures Design Laboratory course at M.A.M. School of Engineering, detailing objectives, experiments, and outcomes for students. It includes a syllabus with various programming tasks in Python, such as implementing ADTs, sorting algorithms, and data structures like stacks, queues, trees, and graphs. The manual is aimed at helping students develop practical skills in data structure design and implementation.

Uploaded by

Iniyavanibtech
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/ 51

lOMoARcPSD|51028987

AD3271-DSD LAB Manual - Good

Data structures design (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)
lOMoARcPSD|51028987

M.A.M. SCHOOL OF ENGINEERING


Accredited by NAAC
Approved by AICTE, New Delhi; Affiliated to Anna University, Chennai
Siruganur, Trichy -621 105.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE & DATA


SCIENCE

REGULATION - 2021

AD3271 – DATA STRUCTURE DESIGN LABORATORY

I Year/ II Semester

Lab Manual

Prepared by
K.Sathish Kumar, AP/CSE

HOD PRINCIPAL

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

SYLLABUS

AD3271 DATA STRUCTURES DESIGN LABORATORY LTPC


0 0 42

OBJECTIVES:
• To implement ADTs in Python.
• To design and implement linear data structures – lists, stack and queues.
• To implement sorting, searching and hashing algorithms.
• To solve problem using tree structures.
• To solve problem using graph structures.

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 & Queue ADTs.
6. Application of Stack & Queue ADTs.
7. Implementation of Sorting and searching algorithms.
8. Implementation of Hash tables.
9. Tree representation and traversal algorithm.
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 algorithm.
TOTAL PERIODS: 60

OUTCOMES:
Upon completion of the course, the students will be able to

• Implement ADTs as Python classes.


• Design, implement and analyze linear data structures such as lists, queues and
stack,according to the needs of different application.
• Design, implement and analyze efficient tree structures to meet requirements such
assearching indexing and sorting.
• Model problems as graph problems and implement efficient Graph algorithms to
solve them.

LIST OF EQUIPMENTS FOR A BATCH OF 30 STUDENTS:

Standalone desktops with Python 30 Nos.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

INDEX

S.No. LIST OF EXPERIMENTS PAGE MARKS SIGNATURE

1 Implement simple ADTs as Python classes


2 Implement Recursive Algorithms in Python
a) Finding the Factorial of a given number
b) Implementation of Fibonacci series
3 Implement List ADT using Python arrays
4 Linked list Implementations of List
5 Implementation of Stack & Queue ADTs
a) Implementation of Stack ADTs
b) Implementation of Queue ADTs
6 Application of Stack & Queue ADTs
a) Implementation of Balancing Symbols
b) Implementation of Priority Scheduling
7 Implementation of Sorting and Searching
Algorithms
a) Implementation of Bubble Sort
b) Implementation of Insertion Sort
c) Implementation of Selection Sort
d) Implementation of Merge Sort
e) Implementation of Quick Sort
f) Implementation of Linear Search
g) Implementation of Binary Search
8 Implementation of Hash Tables
9 Tree Representation and Traversal Algorithm
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
Algorithm

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 1 Implementation of simple ADTs as Python classes

Aim: Write a Python Program to implement ADTs as Python classes.

Algorithm:

Step 1. Start the program


Step 2. Create classes of ADT
Step 3. Access the classes
Step 4. Print the statement
Step 5. Stop the program

Program:

class perimeter():
height=float(input("Enter the height ="))
width=float(input("Enter the width ="))
perim= (height*2)+(width*2)
print("Perimeter = ",perim)
class area(perimeter):
def fun(self):
area1=ar.height*ar.width
print("Area = ",area1)
ar=area()
ar.fun()

Output :

Enter the height = 10


Enter the width = 5
Perimeter = 30.0
Area = 50.0

Result:
Thus, the above program for ADTs python classes was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 2 a) Implementation of Recursive algorithms in Python


Finding Factorial of a given number

Aim: Write a Python program to implement Factorial using recursive algorithm.

Algorithm :

Step 1: Start
Step 2: Read number n
Step 3: Call factorial(n)
Step 4: Print factorial f
Step 5: Stop

factorial(n)
Step 1: If n==1 then return 1
Step 2: Else
f=n*factorial(n-1)
Step 3: Return

Program:

def factorial(num):
if (num == 0):
return 1
else:
return num * factorial(num - 1)
print('{}! is {}'.format(4, factorial(4)))
print('{}! is {}'.format(2, factorial(2)))

Output:
4! is 24
2! is 2

Result:
Thus, the above program for implementing factorial using recursion was successfully
completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 2 b) Implementation of Recursive algorithms in Python


Implementation of Fibonacci Series

Aim: Write a Python program to implement Fibonacci Series using recursive algorithm.

Algorithm :

Step-1 Start the Program


Step-2 Call the Procedure Recursive_Fibonacci(n)
int f0, f1
f0 := 0
f1 := 1
Step-3 If(n <= 1):
Step-4 Return n
Step-5 Return Recursive_Fibonacci(n-1) + Recursive_Fibonacci(n-2)
Step-6 Stop the program

Program:

def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(n):
print(fibonacci(i))

Output:

0
1
1
2
3
5

Result:
Thus, the above program for implementing Fibonacci series using recursion
was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 3 Implement List ADT using Python arrays

Aim: Write a Python program to implement List ADT using Python arrays.

Algorithm :

Step-1 Start the Program


Step-2 Import the copy library
Step-3 Create an array using range function
Step-4 Append the array
Step-5 Insert an element in a specified position
Step-6 Remove an element
Step-7 Printing the array in reverse order
Step-8 Stop the program

Program:

import array
arr = array.array('i', [1, 2, 3])
print ("The new created array is : ",end=" ")
for i in range (0, 3):
print (arr[i], end=" ")
print("\r")
arr.append(4)
print("The appended array is : ", end="")
for i in range (0, 4):
print (arr[i], end=" ")
arr.insert(2, 5)
print("\r")
print ("The array after insertion is : ", end="")
for i in range (0, 5):
print (arr[i], end=" ")
print("\r")
print ("The popped element is : ",end="")
print (arr.pop(2));
# printing array after popping
print ("The array after popping is : ",end="")
for i in range (0,4):
print (arr[i],end=" ")
print("\r")
# using remove() to remove 1st occurrence of 1
arr.remove(1)
# printing array after removing
print ("The array after removing is : ",end="")

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

for i in range (0,3):


print (arr[i],end=" ")
arr.reverse()
# printing array after reversing
print("\r")
print ("The array after reversing is : ",end="")
for i in range (0,3):
print (arr[i],end=" ")

Output :

The new created array is : 1 2 3

The appended array is : 1 2 3 4

The array after insertion is : 1 2 5 3 4

The popped element is : 5


The array after popping is : 1

The array after removing is : 2 3 4

The array after reversing is : 4 3 2

Result:
Thus, the above program for implementing List ADT using Python arrays was
successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 4 Linked list Implementations of List

Aim: Write a Python Program for Linked list Implementations of List.

Algorithm :

Step-1 Start the Program


Step-2 Declare the class
Step-3 Insert the elements in the list
Step-4 Display the elements present in the list
Step-5 Creating a header node
Step-6 Convert the given array to list
Step-7 Stop the program

Program:

class Node:
def __init__(self, data):
self.data = data
self.next = next
# Function to insert Node
def insert(root, item):
temp = Node(0)
temp.data = item
temp.next = root
root = temp
return root
def display(root):
while (root != None):
print(root.data, end=" ")
root = root.next
def arrayToList(arr, n):
root = None
for i in range(n - 1, -1, -1):
root = insert(root, arr[i])
return root
# Driver code
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5];
n = len(arr)
root = arrayToList(arr, n);
display(root)

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

Output :

12345

Result:
Thus, the above program for program for Linked list implementation of List was
successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 5 a) Implementation of Stack & Queue ADTs


Implementation of Stack ADT

Aim: Write a Python Program to implement Stack ADT.

Algorithm:

Step 1: Start the program


Step 2: Create a class Stack with instance variable items initialized to an empty list.
Step 3: Define methods push, pop and is_empty inside the class Stack.
Step 4: The method push appends data to items.
Step 5: The method pop pops the first element in items.
Step 6: The method is_empty returns True only if items is empty.
Step 7: Create an instance of Stack and present a menu to the user to perform
operations on thestack.
Step 8: Stop the program

Program:

class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
s = Stack()
while True:
print('push <value>')
print('pop')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'push':
s.push(int(do[1]))
elif operation == 'pop':
if s.is_empty():
print('Stack is empty.')
else:
print('Popped value: ', s.pop())
elif operation == 'quit':
break

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

Output :
push <value>
pop
quit
What would you like to do? push 5
push <value>
pop
quit
What would you like to do? push 3
push <value>
pop
quit
What would you like to do? pop
Popped value: 3
push <value>
pop
quit
What would you like to do? pop
Popped value: 5
push <value>
pop
quit
What would you like to do? pop
Stack is empty.
push <value>
pop
quit
What would you like to do? quit

Result:
Thus, the above program for Stack ADT was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 5 b) Implementation of Stack & Queue ADTs


Implementation of Queue ADT

Aim: Write a Python Program to implement Queue ADT.

Algorithm:

Step 1: Start the program


Step 2: Create a class Queue with instance variable items initialized to an empty list.
Step 3: Define methods enqueue, dequeue and is_empty inside the class Queue.
Step 4: The method enqueue appends data to items.
Step 5: The method dequeue dequeues the first element in items.
Step 6: The method is_empty returns True only if items is empty.
Step 7: Create an instance of Queue and present a menu to the user to perform
operations on thequeue.
Step 8: Stop the program

Program:

class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, data):
self.items.append(data)
def dequeue(self):
return self.items.pop(0)
q = Queue()
while True:
print('enqueue <value>')
print('dequeue')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'enqueue':
q.enqueue(int(do[1]))
elif operation == 'dequeue':
if q.is_empty():
print('Queue is empty.')
else:
print('Dequeued value: ', q.dequeue())
elif operation == 'quit':
break

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

Output :

enqueue <value>
dequeue
quit
What would you like to do? enqueue5
enqueue <value>
dequeue
quit
What would you like to do? enqueue 4
enqueue <value>
dequeue
quit
What would you like to do? enqueue 3
enqueue <value>
dequeue
quit
What would you like to do? enqueue 6
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued value: 4
enqueue <value>
dequeue
quit
What would you like to do? quit

Result:
Thus, the above program for Queue ADT was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 6 a) Application of Stack & Queue ADTs


Implementation of Balancing Symbols

Aim: Write a Python Program to implement Balancing Symbols using Stack.

Algorithm:

Step 1: Start the program


Step 2: Declare a character stack S.
Step 3: Now traverse the expression string exp.
Step 4: If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
Step 5: If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack
and if thepopped character is the matching starting bracket then fine else brackets are
not balanced.
Step 6: After complete traversal, if there is some starting bracket left in stack then “not
balanced”
Step 7: Stop the program

Program:

open_list = ["[","{","("]
close_list = ["]","}",")"]
# Function to check parentheses
def check(myStr):
stack = []
for i in myStr:
if i in open_list:
stack.append(i)
elif i in close_list:
pos = close_list.index(i)
if ((len(stack) > 0) and
(open_list[pos] == stack[len(stack)-1])):
stack.pop()
else:
return "Unbalanced"
if len(stack) == 0:
return "Balanced"
else:
return "Unbalanced"
# Driver code
string = "{[]{()}}"
print(string,"-", check(string))
string = "[{}{})(]"
print(string,"-", check(string))
string = "((()"

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

Output :

{[]{()}} - Balanced
[{}{})(] – Unbalanced
((() - Unbalanced

Result:
Thus, the above program for implementing Balancing Symbols using Stack was
successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 6 b) Application of Stack & Queue ADTs


Implementation of FCFS Scheduling

Aim: Write a Python Program to implement FCFS Scheduling using Queue.

Algorithm:

Step 1: Start the program


Step 2: Input the processes along with their burst time(bt)and arrival time(at)
Step 3: Find waiting time for all other processes i.e. fora given process i:
wt[i] = (bt[0] + bt[1] + ...... bt[i-1]) - at[i]
Step 4: Now find turn around time
= waiting_time + burst_time for all processes
Step 5: Average waiting time =
total_waiting_time / no_of_processes
Step 6: Average turn around time =
total_turn_around_time / no_of_processes
Step 7: Stop the program

Program:
def findWaitingTime(processes, n, bt, wt, at):
service_time = [0] * n
service_time[0] = 0
wt[0] = 0
# calculating waiting time
for i in range(1, n):
# Add burst time of previous processes
service_time[i] = (service_time[i - 1] + bt[i - 1])
# Find waiting time for current
# process = sum - at[i]
wt[i] = service_time[i] - at[i]
# If waiting time for a process is in
# negative that means it is already
# in the ready queue before CPU becomes
# idle so its waiting time is 0
if (wt[i] < 0):
wt[i] = 0
# Function to calculate turn around time
def findTurnAroundTime(processes, n, bt, wt, tat):
# Calculating turnaround time by
# adding bt[i] + wt[i]
for i in range(n):
tat[i] = bt[i] + wt[i]

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

# Function to calculate average waiting


# and turn-around times.
def findavgTime(processes, n, bt, at):
wt = [0] * n
tat = [0] * n
# Function to find waiting time
# of all processes
findWaitingTime(processes, n, bt, wt, at)
# Function to find turn around time for
# all processes
findTurnAroundTime(processes, n, bt, wt, tat)
# Display processes along with all details
print("Processes Burst Time Arrival Time Waiting",
"Time Turn-Around Time Completion Time \n")
total_wt = 0
total_tat = 0
for i in range(n):
total_wt = total_wt + wt[i]
total_tat = total_tat + tat[i]
compl_time = tat[i] + at[i]
print(" ", i + 1, "\t\t", bt[i], "\t\t", at[i],
"\t\t", wt[i], "\t\t ", tat[i], "\t\t ", compl_time)
print("Average waiting time = %.5f "%(total_wt /n))
print("\nAverage turn around time = ", total_tat / n)
# Driver code
if __name__ =="__main__":
# Process id's
processes = [1, 2, 3]
n=3
# Burst time of all processes
burst_time = [5, 9, 6]
# Arrival time of all processes
arrival_time = [0, 3, 6]
findavgTime(processes, n, burst_time, arrival_time)

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

Output :

Processes Burst Time Arrival Time WaitingTime Turn-AroundTime CompletionTime

1 5 0 0 5 5
2 9 3 2 11 14
3 6 6 8 14 20

Average waiting time = 3.33333

Average turn around time = 10.0

Result:
Thus, the above program for implementing scheduling using Queue was successfully
completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 7 a) Implementation of Sorting and Searching algorithms


Implementation of Bubble Sort

Aim: Write a Python Program to implement Bubble Sort.

Algorithm:

Step 1: Start the program


Step 2: Get the total number of elements. Get the total number of items in the given list
Step 3: Determine the number of outer passes (n – 1) to be done. Its length is list minus
one
Step 4: Perform inner passes (n – 1) times for outer pass 1. Get the first element value and
compare it with the second value. If the second value is less than the first value, then
swap thepositions
Step 5: Repeat step 3 passes until you reach the outer pass (n – 1). Get the next element in
the list then repeat the process that was performed in step 3 until all the values have
been placed in their correct ascending order.
Step 6: Return the result when all passes have been done. Return the results of the sorted
list
Step 7: Stop the program

Program:
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
if __name__ == "__main__":
arr = [5, 1, 4, 2, 8]
bubbleSort(arr)
print("Sorted array is:")
for i in range(len(arr)):
print("%d" % arr[i], end=" ")

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

Output :

Sorted array is:


12458

Result:
Thus, the above program for implementing Bubble Sort was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 7 b) Implementation of Sorting and Searching algorithms


Implementation of Insertion Sort

Aim: Write a Python Program to implement Insertion Sort.

Algorithm:

Step 1: Start the program


Step 2: If it is the first element, then place it in the sorted sub-array.
Step 3: Pick the next element.
Step 4: Compare the picked element with all the elements in sorted sub-array.
Step 5: Shift all the elements in the sorted sub-array that are greater than the picked
element to besorted.
Step 6: Insert the element at the desired place.
Step 7: Repeat the above steps until the array is completely sorted.
Step 8: Stop the program

Program:

def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >= 0 and key < arr[j] :
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
print ("% d" % arr[i])

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

Output :

5
6
11
12
13

Result:
Thus, the above program for implementing Insertion Sort was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 7 c) Implementation of Sorting and Searching algorithms


Implementation of Selection Sort

Aim: Write a Python Program to implement Selection Sort.

Algorithm:

Step 1: Start the program


Step 2: Get the value of n which is the total size of the array
Step 3: Partition the list into sorted and unsorted sections. The sorted section is
initially emptywhile the unsorted section contains the entire list
Step 4: Pick the minimum value from the unpartitioned section and placed it into
the sortedsection.
Step 5: Repeat the process (n – 1) times until all of the elements in the list have
been sorted.
Step 6: Stop the program

Program:

import sys
A = [64, 25, 12, 22, 11]
# Traverse through all array elements
for i in range(len(A)):
# Find the minimum element in remaining
# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
# Swap the found minimum element with
# the first element
A[i], A[min_idx] = A[min_idx], A[i]
# Driver code to test above
print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i],end=" ")

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

Output :

Sorted array
11 12 22 25 64

Result:
Thus, the above program for implementing Selection Sort was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 7 d) Implementation of Sorting and Searching algorithms


Implementation of Merge Sort

Aim: Write a Python Program to implement Merge Sort.

Algorithm:

Step 1: Start the program


Step 2: Declare array and left, right, mid variable
Step 3: Perform merge function.
if left > rightreturn
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
Step 4: Stop the program

Program:

def mergeSort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
mergeSort(L)
# Sorting the second half
mergeSort(R)
i=j=k=0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
# Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
# Driver Code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)

Output :

Given array is
12 11 13 5 6 7
Sorted array is:
5 7 7 11 12 13

Result:
Thus, the above program for implementing Merge Sort was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 7 e) Implementation of Sorting and Searching algorithms


Implementation of Quick Sort

Aim: Write a Python Program to implement Quick Sort.

Algorithm:

Step 1: Start the program


Step 2: Choose the highest index value has pivot
Step 3: Take two variables to point left and right of the list excluding pivot
Step 4: left points to the low index
Step 5: right points to the high
Step 6: while value at left is less than pivot move right
Step 7: while value at right is greater than pivot move left
Step 8: if both step 6 and step 7 does not match swap left and right
Step 9: if left ≥ right, the point where they met is new pivot
Step 10:Stop the program

Program:

def partition(array, low, high):


# choose the rightmost element as pivot
pivot = array[high]
# pointer for greater element
i = low - 1
# traverse through all elements
# compare each element with pivot
for j in range(low, high):
if array[j] <= pivot:
# If element smaller than pivot is found
# swap it with the greater element pointed by i
i=i+1
# Swapping element at i with element at j
(array[i], array[j]) = (array[j], array[i])
# Swap the pivot element with the greater element specified by i
(array[i + 1], array[high]) = (array[high], array[i + 1])
# Return the position from where partition is done
return i + 1
# function to perform quicksort
def quickSort(array, low, high):
if low < high:
# Find pivot element such that
# element smaller than pivot are on the left
# element greater than pivot are on the right

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

pi = partition(array, low, high)


# Recursive call on the left of pivot
quickSort(array, low, pi - 1)
# Recursive call on the right of pivot
quickSort(array, pi + 1, high)
data = [1, 7, 4, 1, 10, 9, -2]
print("Unsorted Array")
print(data)
size = len(data)
quickSort(data, 0, size - 1)
print('Sorted Array in Ascending Order:')
print(data)

Output :

Unsorted Array
[1, 7, 4, 1, 10, 9, -2]
Sorted Array in Ascending Order:
[-2, 1, 1, 4, 7, 9, 10]

Result:
Thus, the above program for implementing Quick Sort was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 7 f) Implementation of Sorting and Searching algorithms


Implementation of Linear Search

Aim: Write a Python Program to implement Linear Search.

Algorithm:

Step 1: Start the program


Step 2: Start searching from the leftmost element of given arr[] and one by one compare
elementx with each element of arr[]
Step 3: If x matches with any of the element, return the index value.
Step 4: If x doesn’t match with any of elements in arr[] , return -1 or element not found.
Step 5: Stop the program

Program:

def linearsearch(arr, x):


for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
print("element found at index "+str(linearsearch(arr,x)))

Output :

element found at index 6

Result:
Thus, the above program for implementing Linear Search was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX. NO: 7 g) Implementation of Sorting and Searching algorithms


Implementation of Binary Search

Aim: Write a Python Program to implement Binary Search.

Algorithm:

Step 1: Start the program


Step 2: Compare x with the middle element.
Step 3: If x matches with the middle element, we return the mid index.
Step 4: Else if x is greater than the mid element, then x can only lie in the right
(greater) halfsubarray after the mid element. Then we apply the algorithm again for
the right half.
Step 5: Else if x is smaller, the target x must lie in the left (lower) half. So we
apply thealgorithm for the left half.
Step 6: Stop the program

Program:

def binary_search(arr, low, high, x):


# Check base case
if high >= low:
mid = (high + low) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it can only
# be present in left subarray
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
# Else the element can only be present in right subarray
else:
return binary_search(arr, mid + 1, high, x)
else:
# Element is not present in the array
return -1
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, 0, len(arr)-1, x)

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")

Output :

Element is present at index 3

Result:
Thus, the above program for implementing Binary Search was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX.NO: 8 Implementation of Hash Tables

Aim: To write a python program to implement hash table

Algorithm:

Step 1: Start the program


Step 2: Create a structure, data (hash table item) with key and value as data.
Step 3: Now create an array of structure, data of some certain size (10, in this case). But,
the size of array must be immediately updated to a prime number just greater than
initial array capacity (i.e 10, in this case).
Step 4: A menu is displayed on the screen.
Step 5: User must choose one option from four choices given in the menu Step 6: Perform
all the operations
Step 7: Stop the program

Program :

hashTable = [[],] * 10
def checkPrime(n):
if n == 1 or n == 0:
return 0
for i in range(2, n//2):
if n % i == 0:
return 0
return 1
def getPrime(n):
if n % 2 == 0:
n=n+1
while not checkPrime(n):
n += 2
return n
def hashFunction(key):
capacity = getPrime(10)
return key % capacity
def insertData(key, data):
index = hashFunction(key)
hashTable[index] = [key, data]
def removeData(key):
index = hashFunction(key)
hashTable[index] = 0
insertData(123, "apple")

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

insertData(432, "mango")
insertData(213, "banana")
insertData(654, "guava")
print(hashTable)
removeData(123)
print(hashTable)

Output:

[[], [], [123, 'apple'], [432, 'mango'], [213, 'banana'], [654, 'guava'], [], [], [], []]
[[], [], 0, [432, 'mango'], [213, 'banana'], [654, 'guava'], [], [], [], []]

Result:
Thus, the python program to implement hash table is executed successfully and output
isverified.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX.NO:9 Implementation of Representation and Traversal Algorithm

Aim: To write a python program to implement tree representation and traversal algorithm.

Pre-order traversal.
Algorithm:
1. Visit the root (we will print it when we visit to show the order of visiting)
2. Traverse the left subtree in pre-order
3. Traverse the right subtree in pre-order
In-order traversal
Visit the root node in between the left and right node (in)
Algorithm:
1. Traverse the left subtree in in-order
2. Visit the root (we will print it when we visit to show the order of visiting)
3. Traverse the right subtree in in-order
Post-order traversal
Visit the root node after (post) visiting the left and right subtree.
Algorithm:
1. Traverse the left subtree in in-order
2. Traverse the right subtree in in-order
3. Visit the root (we will print it when we visit to show the order of visiting)

Program :

class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left)
print(root.val),
printInorder(root.right)
def printPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
print(root.val),

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

def printPreorder(root):
if root:
print(root.val),
printPreorder(root.left)
printPreorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print ("Preorder traversal of binary tree is")
printPreorder(root)
print ("\nInorder traversal of binary tree is")
printInorder(root)
print ("\nPostorder traversal of binary tree is")
printPostorder(root)

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

Output:

Preorder traversal of binary tree is


1
2
4
5
3
Inorder traversal of binary tree is
4
2
5
1
3
Postorder traversal of binary tree is
4
5
2
3
1

Result:
Thus, the above program for tree representation and traversal algorithm was successfully
completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX.NO:10 Implementation of Binary Search Tree

Aim: To write a python program to implement Binary Search Tree.

Algorithm:

Step 1: Start the program


Step 2: Read the search element
Step 3: Find the middle element in the sorted list
Step 4: Compare the search element with the middle element
i. if both are matching, print element found
ii. else then check if the search element is smaller or larger than the middle
element Step 5: If the search element is smaller than the middle element, then repeat
steps 3 and 4 for the left sublist of the middle element
Step 6: If the search element is larger than the middle element, then repeat steps 3 and 4
for theright sublist of the middle element
Step 7: Repeat the process until the search element if found in the list
Step 8: If element is not found, loop terminates
Step 9: Stop the program

Program:

def binary_search(arr, low, high, x):


# Check base case
if high >= low:
mid = (high + low) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it can only
# be present in left subarray
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
# Else the element can only be present in right subarray
else:
return binary_search(arr, mid + 1, high, x)
else:
# Element is not present in the array
return -1
# Test array

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
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:

Element is present at index 3

Result:
Thus, the above program for binary search tree was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX.NO:11 Implementation of Heaps

Aim: To write a python program to implement of Heap.

Algorithm:

Step 1: Start the program.


Step 2: Create a max-heap from the given array.
Step 3: In a max-heap, largest item is stored at the root of the heap.
Step 4: Replace it with the last item of the heap and reduce the size of heap by 1.
Step 5: Finally, call heapify() to heapify the root of the tree.
Step 6: Go to Step 3 while size of heap is more than 1.
Step 7: Stop the program.

Program:

class MaxHeap:
def __init__(self, maxsize):
self.maxsize = maxsize
self.size = 0
self.Heap = [0] * (self.maxsize + 1)
self.Heap[0] = sys.maxsize
self.FRONT = 1
# Function to return the position of
# parent for the node currently
# at pos
def parent(self, pos):
return pos // 2
# Function to return the position of
# the left child for the node currently
# at pos
def leftChild(self, pos):
return 2 * pos
# Function to return the position of
# the right child for the node currently
# at pos
def rightChild(self, pos):
return (2 * pos) + 1
# Function that returns true if the passed
# node is a leaf node
def isLeaf(self, pos):
if pos >= (self.size//2) and pos <= self.size:

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

return True
return False
# Function to swap two nodes of the heap
def swap(self, fpos, spos):
self.Heap[fpos], self.Heap[spos] = (self.Heap[spos],
self.Heap[fpos])
# Function to heapify the node at pos
def maxHeapify(self, pos):
# If the node is a non-leaf node and smaller
# than any of its child
if not self.isLeaf(pos):
if (self.Heap[pos] < self.Heap[self.leftChild(pos)] or
self.Heap[pos] < self.Heap[self.rightChild(pos)]):
# Swap with the left child and heapify
# the left child
if (self.Heap[self.leftChild(pos)] >
self.Heap[self.rightChild(pos)]):
self.swap(pos, self.leftChild(pos))
self.maxHeapify(self.leftChild(pos))
# Swap with the right child and heapify
# the right child
else:
self.swap(pos, self.rightChild(pos))
self.maxHeapify(self.rightChild(pos))
# Function to insert a node into the heap
def insert(self, element):
if self.size >= self.maxsize:
return
self.size += 1
self.Heap[self.size] = element
current = self.size
while (self.Heap[current] >
self.Heap[self.parent(current)]):
self.swap(current, self.parent(current))
current = self.parent(current)
# Function to print the contents of the heap
def Print(self):
for i in range(1, (self.size // 2) + 1):
print("PARENT : " + str(self.Heap[i]) +
"LEFT CHILD : " + str(self.Heap[2 * i]) +
"RIGHT CHILD : " + str(self.Heap[2 * i + 1]))
# Function to remove and return the maximum
# element from the heap
def extractMax(self):
popped = self.Heap[self.FRONT]
self.Heap[self.FRONT] = self.Heap[self.size]

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

self.size -= 1
self.maxHeapify(self.FRONT)
return popped
# Driver Code

if __name__ == "__main__":
print('The maxHeap is ')
maxHeap = MaxHeap(15)
maxHeap.insert(5)
maxHeap.insert(3)
maxHeap.insert(17)
maxHeap.insert(10)
maxHeap.insert(84)
maxHeap.insert(19)
maxHeap.insert(6)
maxHeap.insert(22)
maxHeap.insert(9)
maxHeap.Print()
print("The Max val is " + str(maxHeap.extractMax()))

Output:

The maxHeap is
PARENT : 84LEFT CHILD : 22RIGHT CHILD : 19PARENT : 22LEFT CHILD :
17RIGHT CHILD : 10PARENT : 19LEFT CHILD : 5RIGHT CHILD : 6 PARENT :
17LEFT CHILD : 3RIGHT CHILD : 9
The Max val is 84

Result:
Thus, the above program for heap was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX.NO: 12 a) Graph Representation and Traversal Algorithms


Implementation of Breadth-First Search (BFS)

Aim: To write a python program to implement Breadth-first search (BFS).

Algorithm:

Step 1: Start the program.


Step 2: Pick any node, visit the adjacent unvisited vertex, mark it as visited, display it,
and insertit in a queue.
Step 3: If there are no remaining adjacent vertices left, remove the first vertex from the
queue.
Step 4: Repeat step 2 and step 3 until the queue is empty or the desired node is found.
Step 5: Stop the program.

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:
ABCDEF

Result:
Thus, the above program for Breadth-first search was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX.NO: 12 b) Graph Representation and Traversal Algorithms


Implementation of Depth-First Search (DFS)

Aim: To write a python program to implement Depth first search (DFS)

Algorithm:
Step 1: Start the program.
Step 2: Pick any node. If it is unvisited, mark it as visited and recur on all its adjacent
nodes.
Step 3: Repeat until all the nodes are visited, or the node to be searched is found.
Step 4: Stop the program.

Program:

graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : [] }
visited = set() # Set to keep track of visited nodes.
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# Driver Code
dfs(visited, graph, 'A')

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

Output:

Result:
Thus, the above program for Depth-first search was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX.NO: 13 Implementation of Single Source Shortest Path Algorithm


- Dijkstra’s Algorithm

Aim: To write a python program to implement of single source shortest path algorithm.

Algorithm:
Step 1: Start the program.
Step 2: Create a set sptSet (shortest path tree set) that keeps track of vertices included in
shortest path tree, i.e., whose minimum distance from source is calculated and
finalized. Initially, this set is empty.
Step 3: Assign a distance value to all vertices in the input graph. Initialize all distance
values as INFINITE. Assign distance value as 0 for the source vertex so that it is
picked first.
Step 4: While sptSet doesn’t include all vertices:
• Pick a vertex u which is not there in sptSet and has minimum distance value.
• Include u to sptSet.
• Update distance value of all adjacent vertices of u. To update the distance values,
iterate through all adjacent vertices. For every adjacent vertex v, if the sum of a
distance value of u (from source) and weight of edge u-v, is less than the distance
value of v, then update the distance value of v.
Step 5: Stop the program

Program:

# Python program for Dijkstra's single


class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
def printSolution(self, dist):
print("Vertex \t Distance from Source")
for node in range(self.V):
print(node, "\t\t", dist[node])
# A utility function to find the vertex with
# minimum distance value, from the set of vertices
# not yet included in shortest path tree
def minDistance(self, dist, sptSet):
# Initialize minimum distance for next node
min = 1e7
# Search not nearest vertex not in the

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

# shortest path tree


for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index
# Function that implements Dijkstra's single source
# shortest path algorithm for a graph represented
# using adjacency matrix representation
def dijkstra(self, src):
dist = [1e7] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
# Pick the minimum distance vertex from
# the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minDistance(dist, sptSet)
# Put the minimum distance vertex in the
# shortest path tree
sptSet[u] = True
# Update dist value of the adjacent vertices
# of the picked vertex only if the current
# distance is greater than new distance and
# the vertex in not in the shortest path tree
for v in range(self.V):
if (self.graph[u][v] > 0 and
sptSet[v] == False and
dist[v] > dist[u] + self.graph[u][v]):
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)
# Driver program
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
g.dijkstra(0)

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

Output:

Vertex Distance from Source


0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14

Result:
Thus, the above program for implementation of single source shortest path algorithm
was successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

EX.NO: 14 Implementation of Minimum Spanning Tree Algorithms


- Prim's Algorithm

Aim: To write a python program to implement of implementation of minimum spanning


tree algorithms.

Algorithm:
Step 1: Start the program
Step 2: Select a random node.
Step 3: Choose the path with the minimum weight connected to the chosen node.
Step 4: The path will lead you to a new node, position yourself there.
Step 5: Once you have formed/updated the initial tree, choose the path with the minimum
weightthat is connected to the whole tree. Keep in mind that you must avoid creating
cycles.
Step 6: Repeat steps 3 and 4 until you have covered all the vertices.
Step 7: Stop the program

Program:

INF = 9999999
# number of vertices in graph
N=5
#creating graph by adjacency matrix method
G = [[0, 19, 5, 0, 0],
[19, 0, 5, 9, 2],
[5, 5, 0, 1, 6],
[0, 9, 1, 0, 1],
[0, 2, 6, 1, 0]]
selected_node = [0, 0, 0, 0, 0]
no_edge = 0
selected_node[0] = True
# printing for edge and weight
print("Edge : Weight\n")
while (no_edge < N - 1):
minimum = INF
a=0
b=0
for m in range(N):
if selected_node[m]:
for n in range(N):
if ((not selected_node[n]) and G[m][n]):
# not in selected and there is an edge

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)


lOMoARcPSD|51028987

if minimum > G[m][n]:


minimum = G[m][n]
a=m
b=n
print(str(a) + "-" + str(b) + ":" + str(G[a][b]))
selected_node[b] = True
no_edge += 1

Output:

Edge : Weight

0-2:5
2-3:1
3-4:1
4-1:2

Result:
Thus, the above program for implementation of minimum spanning tree algorithms was
successfully completed.

Downloaded by Iniyavani R (iniyavanir.cse@mietchennai.in)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy