Daa Program 2
Daa Program 2
Lab-
Algorithm
Practical Note
Book
2024 – 2026
DEPARTMENT OF COMPUTER SCIENCE
2024- 2026
DEPARTMENT OF COMPUTER SCIENCE
2024 – 2026
REG.NO:
1 VARIOUS OPERATIONS
ON STACK
2 VARIOUS OPERATIONS
IN QUEUE
3 TOWER OF HANOI
PROBLEM
5 SEARCHING AN ELEMENT
IN A TREE USING DIVIDE
AND CONQUER STRATEGY
6 MERGE SORT
7 KNAPSACK PROBLEM
8 SALESMEN PROBLEM
9 8*8 MATRICES
EX NO: 1
DATE:
ALGORITHM:
def delete(stack):
global top
if top == 0:
print("Stack is empty")
else:
top = top - 1
print("The deleted element is", stack.pop())
def display(stack):
print("The stack elements are:", stack)
while True:
print ("Stack operations")
print ("1. Insertion")
print ("2. Deletion")
print ("3. Display")
print ("4. Exit")
print ("Enter your choice: ")
choice = int(input())
if choice == 1:
print ("The stack elements are:", stack)
x = int (input("Enter the data: "))
insert (stack, x)
elif choice == 2:
delete(stack)
elif choice == 3:
display(stack)
elif choice == 4:
break
else:
print ("Invalid choice")
OUTPUT:
EX NO: 2
DATE:
ALGORITHM:
ALGORITHMS:
STEP 1: Start the process.
STEP 2: Define a function tower of Hanoi that takes the number of disks n,
source, auxiliary, and target pegs as parameters.
STEP 3: If there’s only one disk (base case), print the move from the source peg
to the target peg.
STEP 4: For more than one disk, recursively move the top n-1 disks from the
source to the auxiliary peg.
STEP 5: Print the move of the nth disk from the source to the target peg.
STEP 6: Recursively move the n-1 disks from the auxiliary peg to the target
peg.
STEP 7: Set the number of disks n and pegs for source, auxiliary, and target.
STEP 8: Call the function to solve the Tower of Hanoi problem with the
provided parameters.
STEP 9: Stop the Process.
CODING:
def tower_of_hanoi(n, source, auxiliary, target):
if n == 1:
print("Move disk 1 from {} to {}".format(source, target))
return
tower_of_hanoi(n - 1, source, target, auxiliary)
print("Move disk {} from {} to {}".format(n, source, target))
tower_of_hanoi(n - 1, auxiliary, source, target)
n=3
source_peg = "A"
auxiliary_peg = "B"
target_peg = "C"
tower_of_hanoi(n, source_peg, auxiliary_peg, target_peg)
OUTPUT:
EX NO: 4
DATE:
SORTING OF ARRAY USING QUICK SORT
AIM:
To write a program to sort an array of an elements using quick sort.
ALGORITHM
STEP 3: Check if the array has one or zero elements (base case), return it.4
STEP 5: Partition the array into two subarrays: elements less than the pivot.
STEP 6: Partition the array into another subarray: elements greater than or
equal to the pivot.
STEP 7: Recursively call quick sort on the left subarray.
STEP 8: Recursively call quick sort on the right subarray.
STEP 9: Combine the sorted left subarray, pivot, and sorted right subarray.
STEP 10: Return the combined sorted array.
CODING:
def partition(a,m,q):
v = a[m]
i=m
j=q
while i <=j:
while a[i] < v:
i=i+1
while a[j] > v:
j=j-1
if i < j:
a[i], a[j] = a[j], a[i]
else:
return j
def quick_sort(a,low,high):
if low < high:
mid = partition(a, low, high)
quick_sort(a, low, mid - 1)
quick_sort(a, mid + 1, high)
print("Enter the size of the input data:")
n = int(input())
a = []
STEP 2: Define a function binary (a, x, n) that takes the sorted array a, the
target element x, and the array size n.
STEP 3: Initialize two variables: low = 0 and high = n - 1 to set the boundaries
of the search range.
STEP 4: Enter a while loop that continues as long as low <= high
(search space is valid).
STEP 7: If x < a[mid], set high = mid - 1 to search the left half; otherwise, set
low = mid + 1 to search the right half.
STEP 8: If the element is not found (loop ends without returning), return 1 to
the element is not present.
ALGORITHM:
STEP 1: Start the process.
STEP 2: Define a recursive function for merge sort
STEP 3: Check if the array has one or zero elements (base case), return it.
STEP 4: Split the array into two halves.
STEP 5: Recursively call merge sort on the left half.
STEP 6: Recursively call merge sort on the right half.
STEP 7: Merge the sorted halves
STEP 8: Initialize pointers for both halves and a result array, Compare
elements from both halves, adding the smaller element to the result and
Append any remaining elements from either half to the result.
STEP 9: Stop the process.
CODING:
def merge(low, mid, high):
i = low
k = low
j = mid + 1
def merge_sort(low,high):
if(low<high):
mid = (low+high)//2
merge_sort(low,mid)
merge_sort(mid+1,high)
merge(low,mid,high)
a = []
b = []
print("Enter the no of elements to be sorted: ")
n = int(input())
print("Enter the elements:")
for i in range(n):
value = int(input())
a.append(value)
b.append(0)
low = 0
high = n - 1
merge_sort(low,high)
print("Sorted list:",a)
OUTPUT:
EX NO:7
DATE:
KNAPSACK PROBLEM
AIM:
To write a program to solve the knapsack problem using greedy method.
ALGORITHM:
STEP 4: For each item, iterate through possible weights from 1 to capacity.
STEP 5: Check if the current item's weight is less than or equal to the current
capacity.
STEP 7: Update the dp table with the maximum value for the current weight.
STEP 9:. Return the value in the last cell of the dp table as the result.
CODING:
def greedy_knapsack(weights, values, capacity):
n = len(weights)
x = [0.0] * n
u = capacity
for i in range(n):
if weights[i] > u:
break
x[i] = 1.0
u -= weights[i]
if i < n and u > 0:
x[i] = u / weights[i]
u=0
return x
def tsp_nearest_neighbor(distance_matrix):
n = len(distance_matrix) # Number of cities
visited = [False] * n
path = []
total_distance = 0
print("Path:", path)
print("Total Distance:", total_distance)
OUTPUT:
EX NO: 9
DATE:
PROGRAM USING INHERITANCE
AIM:
To write a python program using Inheritance.
ALGORITHM:
STEP 1: Initialize an empty 8x8 chessboard.
STEP 2: Place the first queen in the first row, first column.
STEP 3: Move to the next row and attempt to place a queen in the first
available column.
STEP 5: For each row, repeat the process until all 8 queens are placed.
STEP 6: If you reach the last row and no conflicts occur, output the solution.
STEP 9: Return all solutions once all queens are placed without conflict.
CODING:
for j in range(k):
return False
return True
for i in range(n):
if place(k, i, x):
x[k] = i
if k == n - 1:
for i in range(n):
row = ['.'] * n
row[x[i]] = 'Q'
print(" ".join(row))
print("\n")
else:
NQueens(k + 1, n, x)
def solve_8_queens():
n=8
x = [-1] * n
NQueens(0, n, x)
solve_8_queens()
OUTPUT: