Adsa Manual
Adsa Manual
AIM:
ALGORITHM:
● The Fibonacci function takes an integer n as input and returns the nth
Fibonacci number.
● It uses recursion to calculate the Fibonacci number based on the algorithm
you provided.
1
PROGRAM:
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
# Example usage
n = int(input("Enter the value of n for Fibonacci series: "))
result = fibonacci(n)
print(f"The {n}th Fibonacci number is: {result}")
2
OUTPUT
RESULT:
Thus the python program to implement Fibonacci number using Recursion was written,
executed and Verified successfully.
3
Ex.No: 2 IMPLEMENTATION OF FIBONACCI NUMBER
USING ITERATION
Date:
AIM:
ALGORITHM:
4
PROGRAM:
class Node:
def __init__(self, key):
self.data = key
self.left = self.right = None
def preorder(root):
if root is not None:
print(root.data, end=" ")
preorder(root.left)
preorder(root.right)
# Example usage
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.left = Node(5)
root.right.right = Node(6)
root.right.left.left = Node(7)
root.right.left.right = Node(8)
print("Preorder Traversal:")
preorder(root)
5
OUTPUT
Preorder Traversal:
12435786
RESULT:
Thus the python program to implement Fibonacci number using Recursion was written,
executed and Verified successfully.
6
Ex.No: 3a IMPLEMENTATION OF MERGE SORT
ANALYSIS
Date:
AIM:
ALGORITHM:
● The merge_sort function recursively divides the array into halves until it
contains only one element.
● The merge function is responsible for merging two sorted halves into a single
sorted array.
7
PROGRAM:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2 # Calculate the middle index
# Compare elements from left and right halves and merge in sorted order
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
# Copy the remaining elements from left and right halves, if any
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
merge_sort(arr)
8
OUTPUT
RESULT:
Thus the python program to implement Fibonacci number using Recursion was written,
executed and Verified successfully.
9
Ex.No: 3b IMPLEMENTATION OF QUICK SORT
ANALYSIS
Date:
AIM:
ALGORITHM:
10
PROGRAM:
def quick_sort(arr):
if len(arr) <= 1:
return arr # Base case: already sorted if the array has 0 or 1 element
else:
pivot = arr[len(arr) // 2] # Choose the middle element as the pivot
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
sorted_array = quick_sort(arr)
11
OUTPUT
RESULT:
Thus the python program to implement Fibonacci number using Recursion was written,
executed and Verified successfully.
12
Ex.No: 4 IMPLEMENTATION OF BINARY SEARCH TREE
Date:
AIM:
ALGORITHM:
13
PROGRAM:
class Node:
def __init__(self, key):
self.key = key
self.left = self.right = None
if result:
print(f"Element {search_key} found in the BST.")
else:
print(f"Element {search_key} not found in the BST.")
14
OUTPUT
.
RESULT:
Thus the implementation of Binary Search tree was written, executed and verified
successfully.
15
Ex.No: 5 RED BLACK TREE IMPLEMENTATION
Date:
AIM:
ALGORITHM:
● The insert method is used to insert elements into the Red-Black Tree.
● The inorder_traversal method is used to visualize the Red-Black Tree using
inorder traversal.
16
PROGRAM:
class Node:
def __init__(self, key, color='R'):
self.key = key
self.left = self.right = self.parent = None
self.color = color
class RedBlackTree:
def __init__(self):
self.NIL = Node(None, 'B') # NIL represents a null node
self.root = self.NIL
node.parent = y
if y == None:
self.root = node
elif node.key < y.key:
y.left = node
else:
y.right = node
17
while node.parent and node.parent.color == 'R':
if node.parent == node.parent.parent.left:
y = node.parent.parent.right
if y and y.color == 'R':
node.parent.color = 'B'
y.color = 'B'
node.parent.parent.color = 'R'
node = node.parent.parent
else:
if node == node.parent.right:
node = node.parent
self.left_rotate(node)
node.parent.color = 'B'
node.parent.parent.color = 'R'
self.right_rotate(node.parent.parent)
else:
y = node.parent.parent.left
if y and y.color == 'R':
node.parent.color = 'B'
y.color = 'B'
node.parent.parent.color = 'R'
node = node.parent.parent
else:
if node == node.parent.left:
node = node.parent
self.right_rotate(node)
node.parent.color = 'B'
node.parent.parent.color = 'R'
self.left_rotate(node.parent.parent)
if y.left != self.NIL:
y.left.parent = x
y.parent = x.parent
if x.parent == None:
self.root = y
elif x == x.parent.left:
x.parent.left = y
else:
18
x.parent.right = y
y.left = x
x.parent = y
if y.right != self.NIL:
y.right.parent = x
y.parent = x.parent
if x.parent == None:
self.root = y
elif x == x.parent.right:
x.parent.right = y
else:
x.parent.left = y
y.right = x
x.parent = y
# Example usage
rb_tree = RedBlackTree()
keys = [50, 30, 20, 40, 70, 60, 80]
19
OUTPUT
RESULT:
Thus the python program to implement Red Black Tree was executed and verified
successfully.
20
Ex.No: 6 HEAP IMPLEMENTATION
Date:
AIM:
ALGORITHM:
21
PROGRAM:
def buildMaxHeap(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
heapSort(arr)
22
OUTPUT
RESULT:
Thus the heap implementation was written, executed and verified successfully.
23
Ex.No: 7 FIBONACCI HEAP IMPLEMENTATION
Date:
AIM:
ALGORITHM:
Initialization:
● FibonacciNode class represents a node in the Fibonacci Heap.
● FibonacciHeap class represents the Fibonacci Heap itself.
● Each node has a key, degree, marked status, references to child, parent,
next, and prev nodes.
● The heap has a min_node representing the minimum node and keeps
track of the number of nodes.
Insertion (insert method):
● Inserts a new node with the given key into the heap.
● If the heap is empty, the new node becomes the min_node.
● Otherwise, the new node is linked into the circular doubly linked list
using the _link method, and if its key is smaller than the current
minimum, it becomes the new minimum.
Finding Minimum (minimum method):
● Returns the key of the minimum node in the heap.
Extracting Minimum (extractMin method):
● Removes and returns the node with the minimum key from the heap.
● If the minimum node has children, they are added to the root list.
● The minimum node is removed from the root list, and consolidation is
performed using the _consolidate method to ensure that there is at
most one tree of each degree.
Decreasing Key (decreaseKey method):
● Decreases the key of a node to a new value.
● If the new key is smaller than the current key, the node is cut from its
parent and possibly marked. Cascading cuts are performed using the
_cut and _cascading_cut methods.
Deletion (delete method):
● Deletes a node from the heap by decreasing its key to negative infinity
and then extracting the minimum.
Union (union method):
● Merges another Fibonacci Heap with the current heap by linking their
root lists.
24
Linking (_link method):
● Links two trees of the same degree together.
Cutting (_cut method):
● Cuts the link between a child and its parent, making the child a new
root.
Cascading Cut (_cascading_cut method):
● Ensures that no tree in the heap has lost two children by performing
cascading cuts.
Consolidation (_consolidate method):
● Consolidates trees of the same degree to ensure there is at most one
tree of each degree.
Example Usage and Output:
● The code includes an example where keys are inserted into the
Fibonacci Heap, the minimum key is printed, and then keys are
extracted in increasing order.
Feel free to use this explanation as a guide for your lab report or to ask any specific
questions you might have!
25
PROGRAM:
class FibonacciNode:
def __init__(self, key):
self.key = key
self.degree = 0
self.marked = False
self.child = None
self.parent = None
self.next = self
self.prev = self
class FibonacciHeap:
def __init__(self):
self.min_node = None
self.num_nodes = 0
def minimum(self):
return self.min_node.key if self.min_node else None
def extractMin(self):
min_node = self.min_node
if min_node:
if min_node.child:
child = min_node.child
while child.parent:
next_child = child.next
min_node.child = next_child
self._add_node(child)
child.parent = None
child = next_child
prev_node = min_node.prev
next_node = min_node.next
26
prev_node.next = next_node
next_node.prev = prev_node
if min_node == min_node.next:
self.min_node = None
else:
self.min_node = next_node
self._consolidate()
self.num_nodes -= 1
node.key = new_key
parent = node.parent
27
node.next = node
node.prev = node
if parent.child == child:
parent.child = next_child
parent.degree -= 1
self._add_node(child)
child.parent = None
child.marked = False
def _consolidate(self):
max_degree = int(self.num_nodes**0.5) + 1
degree_array = [None] * max_degree
current = self.min_node
nodes = []
28
degree_array[degree] = node
self.min_node = None
for degree_node in degree_array:
if degree_node:
if self.min_node:
self._link(self.min_node, degree_node)
if degree_node.key < self.min_node.key:
self.min_node = degree_node
else:
self.min_node = degree_node
29
OUTPUT
RESULT:
Thus the Fibonacci heap implementation was written, executed and verified successfully.
30
Ex.No: 8a GRAPH TRAVERSALS (DEPTH FIRST SEARCH)
Date:
AIM:
To write a python program to implement graph traversal by using depth first search.
ALGORITHM:
31
PROGRAM:
class Graph:
def __init__(self):
self.graph = defaultdict(list)
while stack:
current_node = stack.pop()
if current_node not in visited:
print(current_node, end=" ")
visited.add(current_node)
32
OUTPUT:
RESULT:
Thus the python program to implement graph traversal by using depth first search was
written and verified successfully.
33
Ex.No: 8b GRAPH TRAVERSALS (BREADTH FIRST SEARCH)
Date:
AIM:
ALGORITHM:
34
PROGRAM :
class Graph:
def __init__(self):
self.graph = defaultdict(list)
while queue:
current_node = queue.popleft()
if current_node not in visited:
print(current_node, end=" ")
visited.add(current_node)
35
OUTPUT
RESULT:
Thus the python program to implement graph traversal by using breadth first search was
written, executed and verified successfully.
36
Ex.No: 9a
SPANNING TREE IMPLEMENTATION (KRUSKAL’S ALGORITHM)
Date:
AIM:
ALGORITHM:
• The Graph class initializes the graph with a given number of vertices.
• The add_edge method adds edges to the graph.
• The find_parent and union methods are used for finding the parent and
union operations in the disjoint-set data structure.
• The kruskal method implements Kruskal's algorithm to find the minimum
spanning tree.
• The example usage creates a graph and finds the minimum spanning tree
using Kruskal's algorithm.
37
PROGRAM:
class Graph:
def __init__(self):
self.graph = defaultdict(list)
while queue:
current_node = queue.popleft()
if current_node not in visited:
print(current_node, end=" ")
visited.add(current_node)
38
OUTPUT
RESULT:
Thus the Spanning tree implementation using kruskal‟s algorithm was written,
executed and verified successfully.
39
Ex.No: 9b
SPANNING TREE IMPLEMENTATION (PRIM’S ALGORITHM)
Date:
AIM:
To write a python program to implement spanning tree implementation using Prim‟s
algorithm.
ALGORITHM:
• The Graph class initializes the graph with a given number of vertices.
• The add_edge method adds edges to the graph.
• The prim method implements Prim's algorithm to find the minimum spanning
tree.
• The algorithm maintains a set of vertices (mst_set) included in the MST and
uses a min-heap to select the next vertex to be included.
• The example usage creates a graph and finds the weight of the minimum
spanning tree using Prim's algorithm.
40
PROGRAM:
import heapq
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[] for _ in range(vertices)]
def prim(self):
mst_set = set()
min_heap = [(0, 0)] # (key, vertex) - heap to store vertices with their key values
total_weight = 0
key_values = [float('inf')] * self.V
key_values[0] = 0
return total_weight
41
OUTPUT:
RESULT:
Thus the Spanning tree implementation using prim’s algorithm was written,
executed and verified successfully.
42
Ex.No: 10a
SHORTEST PATH ALGORITHM (DIJKSTRA’S ALGORITHM)
Date:
AIM:
ALGORITHM:
• The Graph class initializes the graph with a given number of vertices.
• The add_edge method adds edges to the graph.
• The dijkstra method implements Dijkstra's algorithm to find the shortest
distances from a given source vertex.
• The algorithm uses a min-heap to efficiently select the next vertex with the
smallest temporary distance.
• The example usage creates a graph and finds the shortest distances from a
specified starting vertex.
43
PROGRAM:
import heapq
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[] for _ in range(vertices)]
while min_heap:
dist_u, u = heapq.heappop(min_heap)
return distances
start_vertex = 0
shortest_distances = g.dijkstra(start_vertex)
44
OUTPUT
RESULT:
Thus the python program to implement Dijkstra’s Algorithm was executed and
verified successfully.
45
Ex.No: 10b
SHORTEST PATH ALGARITHMS (BELLMANN FORD ALGORITHM)
Date:
AIM:
ALGORITHM:
• The Graph class initializes the graph with a given number of vertices.
• The add_edge method adds edges to the graph.
• The bellman_ford method implements the Bellman-Ford algorithm to find the
shortest distances from a given source vertex.
• The algorithm iterates through all edges multiple times to relax the path
distances.
• It also checks for negative cycles by iterating through all edges one more
time.
46
PROGRAM:
class Graph:
def __init__(self, vertices):
self.V = vertices
self.edges = []
return distances
start_vertex = 0
shortest_distances = g.bellman_ford(start_vertex)
47
OUTPUT
RESULT:
Thus the python program to implement Bellmann Ford Algorithm was written,
executed and verified successfully
48
Ex.No: 11
MATRIX CHAIN MULTIPLICATION
Date:
AIM:
ALGORITHM:
• A chain of matrices to be multiplied is given as input.
• For a sequence A1,A2,A3,A4 of 4 matrices, there are 5 different orderings=5
different parenthesization.
o (A1,(A2(A3 A4)))
o (A1((A2 A3)A4))
o ((A1 A2)(A3 A4))
o ((A1(A2 A3))A4)
o (((A1 A2)A3)A4)
• Matrix_Multiply(A,B)
• If coloumns[A]!=rows[B]
• Then error “incomplete dimensions”
• Else for i <- 1 to rows[A]
• Do for j <- 1 to columns[B]
• Do c[I,j] <- 0
• For k<- 1 to columns[A]
• Do c[i,j]=C[i,j]+A[i,k]+B[i,j]
• Return c
• A parenthesizing of the chain of the matrices is obtained as output.
49
PROGRAM:
def matrix_chain_multiplication(p):
n = len(p) - 1 # Number of matrices
m = [[0] * (n + 1) for _ in range(n + 1)] # Table to store minimum multiplication cost
s = [[0] * (n + 1) for _ in range(n + 1)] # Table to store split points
return m, s
print("\nOptimal Parenthesization:")
print_optimal_parenthesization(s_table, 1, len(matrix_dimensions) - 1)
50
OUTPUT:
Optimal Parenthesization:
((A1(A2A3))((A4A5)A6))
RESULT:
Thus the python program to implement Matrix Chain Multiplication was written, executed and
verified successfully.
51
Ex.No: 12a
ACTIVITY SELECTION
Date:
AIM:
ALGORITHM:
52
PROGRAM:
# Select new activity if its start time is greater than or equal to the finish time of the last
selected activity
for i in range(1, n):
if activities[i][0] >= selected_activities[-1][1]:
selected_activities.append(activities[i])
return selected_activities
print("Selected Activities:")
for activity in selected_activities:
print(f"Activity {activity[2]} (Start Time: {activity[0]}, Finish Time: {activity[1]})")
53
OUTPUT:
Selected Activities:
Activity 3 (Start Time: 0, Finish Time: 6)
Activity 1 (Start Time: 1, Finish Time: 2)
Activity 4 (Start Time: 5, Finish Time: 7)
Activity 5 (Start Time: 5, Finish Time: 9)
RESULT:
Thus the python program to implement activity selection was executed and verified
successfully
54
Ex.No: 12b
HUFFMAN CODING
Date:
AIM:
ALGORITHM:
55
PROGRAM:
import heapq
from collections import defaultdict
class HuffmanNode:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def build_huffman_tree(freq_map):
priority_queue = [HuffmanNode(char, freq) for char, freq in freq_map.items()]
heapq.heapify(priority_queue)
heapq.heappush(priority_queue, internal_node)
return priority_queue[0]
return mapping
def huffman_coding(text):
freq_map = defaultdict(int)
for char in text:
freq_map[char] += 1
56
root = build_huffman_tree(freq_map)
codes = build_huffman_codes(root)
57
OUTPUT
RESULT:
Thus the python program to implement Huffman Coding was written, executed and verified
successfully.
58
59