0% found this document useful (0 votes)
17 views

MSC FINAL ALGORITHM LAB

Uploaded by

sekar
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)
17 views

MSC FINAL ALGORITHM LAB

Uploaded by

sekar
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/ 21

Page no.

1. THE TOWER OF HANOI USING RECURSION

PROGRAM:

def tower_of_hanoi(n, source, target, auxiliary):

if n == 1:

print(f"Move disk 1 from {source} to {target}")

return

tower_of_hanoi(n - 1, source, auxiliary, target)

print(f"Move disk {n} from {source} to {target}")

tower_of_hanoi(n - 1, auxiliary, target, source)

tower_of_hanoi(3, 'A', 'C', 'B')

OUTPUT:

Move disk 1 from A to C

Move disk 2 from A to B

Move disk 1 from C to B

Move disk 3 from A to C

Move disk 1 from B to A

Move disk 2 from B to C

Move disk 1 from A to C

Department of Computer Science


Page no.

2. TRAVERSE THROUGH BINARY SEARCH TREE USING


TRAVERSALS
PROGRAM:
class Node:
def init (self, key):

self.key = key

self.left = None

self.right = None

class BinarySearchTree:

def init (self):

self.root = None

def insert(self, key):


self.root = self._insert(self.root, key)

def _insert(self, root, key):

if root is None:

return Node(key)

if key < root.key:

root.left = self._insert(root.left, key)

elif key > root.key:

root.right = self._insert(root.right, key)

return root

Department of Computer Science


Page no.

def in_order_traversal(self):

result = []

self._in_order_traversal(self.root, result)

return result

def _in_order_traversal(self, root, result):

if root:

self._in_order_traversal(root.left, result)

result.append(root.key)

self._in_order_traversal(root.right, result)

def pre_order_traversal(self):

result = []

self._pre_order_traversal(self.root, result)

return result

def _pre_order_traversal(self, root, result):

if root:

result.append(root.key)

self._pre_order_traversal(root.left, result)

self._pre_order_traversal(root.right, result)

def post_order_traversal(self):

result = []

self._post_order_traversal(self.root, result)

Department of Computer Science


Page no.

return result
def _post_order_traversal(self, root, result):

if root:

self._post_order_traversal(root.left, result)

self._post_order_traversal(root.right, result)

result.append(root.key)

bst = BinarySearchTree()

keys = [3, 1, 4, 2]

for key in keys:

bst.insert(key)

print("In-order traversal:", bst.in_order_traversal())

print("Pre-order traversal:", bst.pre_order_traversal())

print("Post-order traversal:", bst.post_order_traversal())

OUTPUT:
In-order traversal: [1, 2, 3, 4]
Pre-order traversal: [3, 1, 2, 4]
Post-order traversal: [2, 1, 4, 3]

Department of Computer Science


Page no.

3. TO PERFORM VARIOUS OPERATIONS ON STACK USING LINKED


LIST
PROGRAM:
class Node:
def init (self, data=None):

self.data = data

self.next = None

class Stack:
def init (self):

self.top = None

def is_empty(self):

return self.top is None

def push(self, data):

new_node = Node(data)

new_node.next = self.top

self.top = new_node

def pop(self):
if self.is_empty():

return None

popped_data = self.top.data

self.top = self.top.next

return popped_data

Department of Computer Science


Page no.

def peek(self):
return None if self.is_empty() else self.top.data

def display(self):

current = self.top

while current:

print(current.data, end=" ")

current = current.next

print()

stack = Stack()

print("Is the stack empty?", stack.is_empty())

stack.push(1)

stack.push(2)

stack.push(3)

print("Stack after pushing elements:")

stack.display()

print("Top element:", stack.peek())

popped_element = stack.pop()

print("Popped element:", popped_element)

print("Stack after popping element:")

stack.display()

Department of Computer Science


Page no.

OUTPUT:

Is the stack empty? True

Stack after pushing elements:

321

Top element: 3
Popped element: 3
Stack after popping element:

21

Department of Computer Science


Page no.

4. TO PERFORM VARIOUS OPERATION IN CIRCULAR QUEUE


PROGRAM:
class CircularQueue:
def init (self, capacity):

self.capacity = capacity

self.queue = [None] * capacity

self.front = self.rear = -1

def is_empty(self):

return self.front == -1

def is_full(self):
return (self.rear + 1) % self.capacity == self.front

def enqueue(self, item):

if self.is_full():

print("Queue is full. Cannot enqueue element.")

else:

if self.is_empty():

self.front = self.rear = 0

else:
self.rear = (self.rear + 1) % self.capacity

self.queue[self.rear] = item

print(f"Enqueued: {item}")

Department of Computer Science


Page no.

def dequeue(self):
if self.is_empty():
print("Queue is empty. Cannot dequeue element.")

return None

else:
item = self.queue[self.front]

if self.front == self.rear:

self.front = self.rear = -1

else:

self.front = (self.front + 1) % self.capacity

print(f"Dequeued: {item}")

return item

def display(self):

if self.is_empty():

print("Queue is empty.")

else:
print("Circular Queue:")

i = self.front

while True:

print(self.queue[i], end=" ")

if i == self.rear:

break
i = (i + 1) % self.capacity

print()

cq = CircularQueue(5)

Department of Computer Science


Page no.

print("Is the circular queue empty?", cq.is_empty())

cq.enqueue(1)

cq.enqueue(2)

cq.enqueue(3)

cq.enqueue(4)

cq.display()

cq.dequeue()

cq.display()

cq.enqueue(5)

cq.display()

cq.enqueue(6)

cq.dequeue()

cq.dequeue()

cq.dequeue()

cq.dequeue()

Department of Computer Science


Page no.

OUTPUT:
Is the circular queue empty? True

Enqueued: 1

Enqueued: 2
Enqueued: 3
Enqueued: 4

Circular Queue:

1234

Dequeued: 1

Circular Queue:

234

Enqueued: 5

Circular Queue:

2345

Enqueued: 6
Dequeued: 2
Dequeued: 3
Dequeued: 4
Dequeued: 5

Department of Computer Science


Page no.

5. TO SORT AN ARRAY OF AN ELEMENTS USING QUICK SORT


PROGRAM:
def quick_sort(arr):

if len(arr) <= 1:

return arr

pivot = arr[len(arr) // 2]
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)

array_to_sort = [3, 6, 8, 10, 1, 2, 1]

sorted_array = quick_sort(array_to_sort)

print("Original array:", array_to_sort)

print("Sorted array:", sorted_array)

OUTPUT:

Original array: [3, 6, 8, 10, 1, 2, 1]


Sorted array: [1, 1, 2, 3, 6, 8, 10]

Department of Computer Science


Page no.

6. TO SOLVE NUMBER OF ELEMENTS IN ASCENDING ORDER USING


HEAP SORT
PROGRAM:
def heap_sort(arr):

n = len(arr)

for i in range(n // 2 - 1, -1, -1):

heapify(arr, n, i)

for i in range(n - 1, 0, -1):


arr[i], arr[0] = arr[0], arr[i] element

heapify(arr, i, 0)

def heapify(arr, n, i):

largest = i

left_child = 2 * i + 1

right_child = 2 * i + 2

if left_child < n and arr[left_child] > arr[largest]:

largest = left_child

if right_child < n and arr[right_child] > arr[largest]:

largest = right_child

if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]

heapify(arr, n, largest)

Department of Computer Science


Page no.

array_to_sort = [3, 6, 8, 10, 1, 2, 1]

print("Original array:", array_to_sort)

heap_sort(array_to_sort)

print("Sorted array:", array_to_sort)

OUTPUT:
Original array: [3, 6, 8, 10, 1, 2, 1]
Sorted array: [1, 1, 2, 3, 6, 8, 10]

Department of Computer Science


Page no.

7. TO SOLVE THE KNAPSACK PROBLEM USING GREEDY METHOD


PROGRAM:
def knapsack_fractional_value(weights, values, capacity):

n = len(weights)

ratios = [(values[i] / weights[i], weights[i], values[i]) for i in range(n)]

ratios.sort(reverse=True, key=lambda x: x[0])

total_value = 0.0

knapsack = [0] * n

for i in range(n):
if ratios[i][1] <= capacity:
knapsack[i] = 1 # Take the whole item

total_value += ratios[i][2]

capacity -= ratios[i][1]

else:

knapsack[i] = capacity / ratios[i][1] # Take a fraction of the item

total_value += knapsack[i] * ratios[i][2]

break # The knapsack is full

return knapsack, total_value

weights = [5, 10, 20, 30]

values = [50, 60, 100, 120]


capacity = 50

result, total_value = knapsack_fractional_value(weights, values, capacity)

Department of Computer Science


Page no.

print("Items selected:")

for i in range(len(result)):

print(f"Item {i + 1}: {result[i]:.2f} fraction taken")

print("Total value in the knapsack:", total_value)

OUTPUT:
Items selected:
Item 1: 1.00 fraction taken
Item 2: 1.00 fraction taken
Item 3: 1.00 fraction taken
Item 4: 0.50 fraction taken
Total value in the knapsack: 270.0

Department of Computer Science


Page no.

8. TO SEARCH FOR AN ELEMENT IN A TREE USING DIVIDE&


CONQUER STRATEGY
PROGRAM:
class TreeNode:
def init (self, key):

self.key = key

self.left = None

self.right = None

def search_in_tree(root, target):

if root is None:

return False

if root.key == target:

return True

elif target < root.key:


return search_in_tree(root.left, target)

else:

return search_in_tree(root.right, target)

root = TreeNode(3)

root.left = TreeNode(1)

root.right = TreeNode(4)

root.left.right = TreeNode(2)

target_element = 2

if search_in_tree(root, target_element):

Department of Computer Science


Page no.

print(f"Element {target_element} found in the tree.")

else:

print(f"Element {target_element} not found in the tree.")

OUTPUT:
Element 2 found in the tree.

Department of Computer Science


Page no.

9. TO PLACE THE 8 QUEENS ON AN 8X8 MATRIX SO THAT NO TWO


QUEENS ATTACK
PROGRAM:
def is_safe(board, row, col, n):

for i in range(row):

if board[i][col] == 1:

return False

for i, j in zip(range(row, -1, -1), range(col, -1, -1)):

if board[i][j] == 1:

return False
for i, j in zip(range(row, -1, -1), range(col, n)):

if board[i][j] == 1:

return False

return True

def solve_n_queens_util(board, row, n):

if row == n:

return True

for col in range(n):


if is_safe(board, row, col, n):

board[row][col] = 1

if solve_n_queens_util(board, row + 1, n):

return True

board[row][col] = 0

return False

def solve_n_queens(n):
# Initialize an empty chessboard

board = [[0] * n for _ in range(n)]

Department of Computer Science


Page no.

if not solve_n_queens_util(board, 0, n):

print("No solution exists.")

return

print_solution(board)

def print_solution(board):

for row in board:

print(" ".join(["Q" if cell == 1 else "." for cell in row]))

solve_n_queens(8)

OUTPU

Department of Computer Science


Page no.

Department of Computer Science

You might also like