0% found this document useful (0 votes)
10 views42 pages

ADA LAB Manual-1

The document contains multiple programming assignments completed by Anusha K S for a class, each with specific aims such as sorting algorithms (Selection Sort, Merge Sort, Quick Sort, Insertion Sort), graph algorithms (BFS, DFS, Dijkstra's), and solving problems using backtracking and dynamic programming (N Queens, Knapsack Problem). Each program includes the code, input prompts, and expected outputs. The assignments cover a range of topics in algorithms and data structures, showcasing various techniques and their implementations.
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)
10 views42 pages

ADA LAB Manual-1

The document contains multiple programming assignments completed by Anusha K S for a class, each with specific aims such as sorting algorithms (Selection Sort, Merge Sort, Quick Sort, Insertion Sort), graph algorithms (BFS, DFS, Dijkstra's), and solving problems using backtracking and dynamic programming (N Queens, Knapsack Problem). Each program includes the code, input prompts, and expected outputs. The assignments cover a range of topics in algorithms and data structures, showcasing various techniques and their implementations.
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/ 42

PROGRAM NO:1

AIM: Write a program to sort a list of N elements using Selection Sort


Technique.
DATE: 7-09-23
DONE BY: ANUSHA K S
CLASS:III BCA

import array as ar
def min(A,i,n):
minimum=A[i]
loc=i
for j in range(i+1,n):
if minimum>A[j]:
minimum=A[j]
loc=j
return loc
def sel_sort(A,n):
for i in range(n-1):
loc=min(A,i,n)
temp=A[i]
A[i]=A[loc]
A[loc]=temp
print(A)
A=ar.array('i',[])
n=int(input("Enter the number of elements:"))
print("Enter the elements:")
for i in range(n):
ele=int(input())
A.append(ele)
sel_sort(A,n)

1
OUTPUT:

2
PROGRAM NO:2
AIM: Write a program to read ‘n’ numbers, find minimum and maximum value
in an array using divide and conquer.
DATE: 12-09-23
DONE BY: ANUSHA K S
CLASS:III BCA

import array as ar
def find_min_max(arr,low,high):
if low==high:
return arr[low],arr[low]
if high-low==1:
if arr[low]<arr[high]:
return arr[low],arr[high]
else:
return arr[high],arr[low]
mid=(low+high)//2
min1,max1=find_min_max(arr,low,mid)
min2,max2=find_min_max(arr,mid+1,high)
return min(min1,min2),max(max1,max2)
A=ar.array('i',[])
n=int(input("Enter the number of elements:"))
print("Enter the elements:")
for i in range(n):
ele=int(input(""))
A.append(ele)
min_num,max_num=find_min_max(A,0,n-1)
print("Minimum number:",min_num)
print("Maximum number:",max_num)

3
OUTPUT:

4
PROGRAM NO:3
AIM: Sort a given set of n integer elements using Merge Sort method and
compute its time complexity. Run the program for varied values of n> 5000,
and record the time taken to sort.
DATE: 14-09-23
DONE BY: ANUSHA K S
CLASS:III BCA

import random
import time
def merge_sort(arr):
if len(arr)>1:
mid=len(arr)//2
left_half=arr[:mid]
right_half=arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i<len(left_half)and j<len(right_half):
if left_half[i]<right_half[j]:
arr[k]=left_half[i]
i+=1
else:
arr[k]=right_half[j]
j+=1
k+=1
while i<len(left_half):
arr[k]=left_half[i]
i+=1
k+=1
while j<len(right_half):
arr[k]=right_half[j]

5
j+=1
k+=1
random_numbers=[random.randint(1,1000)for i in range(6000)]
start_time=time.time()
merge_sort(random_numbers)
end_time=time.time()
sorting_time=end_time-start_time
print()
print(f"Time taken to sort list of 6000 random numbers:{sorting_time:.6f}seconds")
print("Merge sort has a time complexity of O(n log n) in the worst, average, and best cases")
print()

6
OUTPUT:

7
PROGRAM NO:4
AIM: Sort a given set of n integer elements using Quick Sort method and
compute its time complexity. Run the program for varied values of n> 5000 and
record the time taken to sort.
DATE: 3-10-23
DONE BY: ANUSHA K S
CLASS:III BCA

import random
import time
def partition(arr,low,high):
pivot=arr[low]
i=low+1
j=high
while True:
while i<=j and arr[i]<=pivot:
i=i+1
while arr[j]>=pivot and j>=i:
j=j-1
if j<i:
break
else:
arr[i],arr[j]=arr[j],arr[i]
arr[low],arr[j]=arr[j],arr[low]
return j
def quick_sort(arr,low,high):
if low<high:
j=partition(arr,low,high)
quick_sort(arr,low,j-1)
quick_sort(arr,j+1,high)
n=int(input("Enter the number of elements:"))
random_number=[random.randint(1,10000) for i in range(n)]

8
start_time=time.time()
quick_sort(random_number,0,n-1)
end_time=time.time()
sorting_time=end_time-start_time
partial_sorted_list=random_number[:20]
print(partial_sorted_list)
print(f"Time taken to sort:{sorting_time:.6f}seconds")

9
OUTPUT:

10
PROGRAM NO:5
AIM: Write a program to sort a list of N elements using Insertion Sort Technique.
DATE: 19-09-23
DONE BY: ANUSHA K S
CLASS:III BCA

def insertion_sort(arr):
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while j>=0 and key<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=key
n=int(input("Enter the number of elements:"))
elements=[]
for i in range(n):
ele=int(input())
elements.append(ele)
print("\nOriginal list:")
print(elements)
insertion_sort(elements)
print("\nSorted list using Insertion sort:")
print(elements)

11
OUTPUT:

12
PROGRAM NO:6
AIM: Write program to implement the BFS algorithm for a graph
DATE: 12-10-23
DONE BY: ANUSHA K S
CLASS:III BCA

def bfs(graph,start):
visited=set()
queue=[]
queue.append(start)
visited.add(start)
while queue:
vertex=queue.pop(0)
print(vertex,end='')
if vertex in graph:
for neighbor in graph[vertex]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
def add_edge(graph,u,v):
if u in graph:
graph[u].append(v)
else:
graph[u]=[v]
def build_graph():
graph={}
num_vertices=int(input("Enter the number of vertices:"))
num_edges=int(input("Enter the number of edges:"))
for _ in range(num_edges):
u,v=map(int,input("Enter an edge(u,v):").split())
if u<=num_vertices and v<=num_vertices:

13
add_edge(graph,u,v)
add_edge(graph,v,u)
else:
print(f"Invalid edge({u},{v}).vertex values must be between 1 and {num_vertices}.")
return graph
graph=build_graph()
start_vertex=int(input("Enter the starting vertex for BFS:"))
print("BFS traversal starting from vertex",start_vertex,":")
bfs(graph,start_vertex)

14
OUTPUT:

15
PROGRAM NO:7
AIM: Write program to implement the DFS algorithm for a graph.
DATE: 12-10-23
DONE BY: ANUSHA K S
CLASS:III BCA

def dfs(graph,start):
visited=set()
stack=[]
stack.append(start)
visited.add(start)
while stack:
vertex=stack.pop()
print(vertex,end='')
if vertex in graph:
for neighbor in reversed(graph[vertex]):
if neighbor not in visited:
stack.append(neighbor)
visited.add(neighbor)
def add_edge(graph,u,v):
if u in graph:
graph[u].append(v)
else:
graph[u]=[v]
def build_graph():
graph={}
num_vertices=int(input("Enter the number of vertices:"))
num_edges=int(input("Enter the number of edges:"))
for _ in range(num_edges):
u,v=map(int,input("Enter an edge(u,v):").split())
if 1<=u<=num_vertices and 1<=v<=num_vertices:

16
add_edge(graph,u,v)
else:
print(f"Invalid edge({u},{v}).vertex values must be between 1 and {num_vertices}.")
return graph
graph=build_graph()
start_vertex=int(input("Enter the starting vertex for DFS:"))
print("DFS traversal starting from vertex",start_vertex,":")
dfs(graph,start_vertex)

17
OUTPUT:

18
PROGRAM NO:8
AIM: Write a program to implement Strassen's Matrix Multiplication of 2*2
Matrixes.
DATE: 17-10-23
DONE BY: ANUSHA K S
CLASS:III BCA

def strassen_matrix_multiply(a,b):
if len(a)!=2 or len(b)!=2:
raise ValueError("Input matrices must be 2*2 matrices")
#Unpack matrix elements
a11,a12,a21,a22=a[0][0],a[0][1],a[1][0],a[1][1]
b11,b12,b21,b22=b[0][0],b[0][1],b[1][0],b[1][1]

#Calculate Strassen's matrix multiplication results


m1=(a11+a22)*(b11+b22)
m2=(a21+a22)*b11
m3=a11*(b12-b22)
m4=a22*(b21-b11)
m5=(a11+a12)*b22
m6=(a21-a11)*(b11+b12)
m7=(a12-a22)*(b21+b22)

#Calculate the resulting 2*2 matrix


c11=m1+m4-m5+m7
c12=m3+m5
c21=m2+m4
c22=m1-m2+m6

#Return the result as a 2*2 matrix


result=[[c11,c12],[c21,c22]]
return result

19
#Input matrices from the user
print("Enter values for the first 2*2 matrix:")
a=[[int(input()),int(input())],[int(input()),int(input())]]

print("Enter values for the second 2*2 matrix:")


b=[[int(input()),int(input())],[int(input()),int(input())]]

#Perform strassen's matrix multiplication


result=strassen_matrix_multiply(a,b)

# Display the entered matrices


print("\nEntered Matrix A:")
for row in a:
print(row)
print("\nEntered Matrix B:")
for row in b:
print(row)

#Display the result


print("Result of matrix multiplication:")
for row in result:
print(row)

20
OUTPUT:

21
PROGRAM NO:1
AIM: Write program to implement backtracking algorithm for solving
problems like N queens.
DATE: 17-10-23
DONE BY: ANUSHA K S
CLASS:III BCA

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):
board=[[0 for _ in range(n)] for _ in range(n)]
if solve_n_queens_util(board,0,n):
for row in board:

22
print(' '.join(['Q' if x==1 else '.' for x in row]))
print()
else:
print("Solution does not exist")
N=int(input("Enter the number of queens:"))
solve_n_queens(N)

23
OUTPUT:

24
PROGRAM NO:2
AIM: Design and implement in to find a subset of a given set S = {Sl, S2,.....,Sn}
of n positive integers whose SUM is equal to a given positive integer d. For
example, if S={1, 2, 5, 6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}.
Display a suitable message, if the given problem instance doesn't have a
solution.
DATE: 31-10-23
DONE BY: ANUSHA K S
CLASS:III BCA

def find_subset_sum(s, n, d, subset=[]):


global flag
if d == 0:
flag = 1
print("Solution found:", subset)
return
if n == 0 or d < 0:
return
subset.append(s[n - 1])
find_subset_sum(s, n - 1, d - s[n - 1], subset)
subset.pop()
find_subset_sum(s, n - 1, d, subset)

flag = 0
s = list(map(int, input("Enter the set of positive integers separated by space:").split()))
d = int(input("Enter the target sum:"))
n = len(s)
print("Possible subset with a sum of", d, "are:")
find_subset_sum(s, n, d)
if flag == 0:
print("No Solution")

25
OUTPUT:

26
PROGRAM NO:3
AIM: Write a program find shortest paths to other vertices using Dijkstra's
algorithm.
DATE: 7-11-23
DONE BY: ANUSHA K S
CLASS:III BCA

def dijkstra(graph,start):
distances={}
for node in graph:
distances[node]=float('infinity')
distances[start]=0
visited=set()
while len(visited)<len(graph):
unvisited_nodes=filter(lambda node:node not in visited,graph)
current_node=min(unvisited_nodes,key=lambda x:distances[x])
visited.add(current_node)
for neighbor,weight in graph[current_node].items():
distance=distances[current_node]+weight
if distance<distances[neighbor]:
distances[neighbor]=distance
return distances
graph={}
num_nodes=int(input("Enter the number of nodes:"))
for _ in range(num_nodes):
node=input(f"Enter the node:")
graph[node]={}
num_neighbor=int(input(f"Enter the number of neighbor for node {node}:"))
for _ in range(num_neighbor):
neighbor,weight=input(f"Enter neighbor and weight(separated by space) for node
{node}:").split()
graph[node][neighbor]=int(weight)

27
start_node=input("Enter the starting node:")
shortest_distances=dijkstra(graph,start_node)
print(f"Shortest distances from node {start_node}:{shortest_distances}")

28
OUTPUT:

29
PROGRAM NO:4
AIM: Write a program to perform Knapsack Problem using Dynamic
Programming.
DATE: 25-11-23
DONE BY: ANUSHA K S
CLASS:III BCA

def knapsack(W, wt, val, n):


k = [[0 for x in range(W + 1)] for x in range(n + 1)]
for i in range(n + 1):
for e in range(W + 1):
if i == 0 or e == 0:
k[i][e] = 0
elif wt[i - 1] <= e:
k[i][e] = max(val[i - 1] + k[i - 1][e - wt[i - 1]], k[i - 1][e])
else:
k[i][e] = k[i - 1][e]
return k[n][W]

n = int(input("Enter the number of items: "))


val = []
wt = []
for i in range(n):
value = int(input(f"Enter the value for item {i + 1}: "))
weight = int(input(f"Enter the weight for item {i + 1}: "))
val.append(value)
wt.append(weight)
W = int(input("Enter the maximum weight capacity of the bag: "))
result = knapsack(W, wt, val, n)
print(f"The maximum value that can be stored in the bag is: {result}")

30
OUTPUT:

31
PROGRAM NO:5
AIM: Write program to implement greedy algorithm for job sequencing with
deadlines.
DATE: 5-12-23
DONE BY: ANUSHA K S
CLASS:III BCA

def jobschedule(array,t):
m=len(array)
for j in range(m):
for q in range(m-1-j):
if array[q][2]<array[q+1][2]:
array[q],array[q+1]=array[q+1],array[q]
res=[False]*t
job=['-1']*t
for q in range(len(array)):
for q in range(min(t-1,array[q][1]-1),-1,-1):
if res[q] is False:
res[q]=True
job[q]=array[q][0]
break
print("Job sequence:",job)
num_jobs=int(input("Enter the number of jobs:"))
array=[]
for i in range(num_jobs):
job_id=input("Enter job ID for job{}:".format(i+1))
time_required=int(input("Enter time requried for job{}:".format(i+1)))
profit=int(input("Enter profit for job{}:".format(i+1)))
array.append([job_id,time_required,profit])
t=int(input("Enter the numbber of time slots:"))
print("Maximum profit sequence of jobs in:")
jobschedule(array,t)

32
OUTPUT:

33
PROGRAM NO:6
AIM: Write a program to perform Travelling Salesman Problem.
DATE: 5-12-23
DONE BY: ANUSHA K S
CLASS:III BCA

from sys import maxsize


from itertools import permutations
def tsp(graph,s):
v=len(graph)
vertex=[i for i in range(v) if i!=s]
min_cost=maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
current_cost=0
k=s
for j in i:
current_cost+=graph[k][j]
k=j
current_cost+=graph[k][s]
min_cost=min(min_cost,current_cost)
return min_cost
v=int(input("Enter the number of vertices:"))
graph=[]
print("Enter the cost matrix:")
for i in range(v):
row=list(map(int,input().split()))
graph.append(row)
s=int(input("Enter the starting vertex:"))
print(tsp(graph,s))

34
OUTPUT:

35
PROGRAM NO:7
AIM: Write a program that implements Prim’s algorithm to generate minimum
cost spanning Tree.
DATE: 5-12-23
DONE BY: ANUSHA K S
CLASS:III BCA

INF=9999999
def get_user_input():
N=int(input("Enter the number of vertices in the graph:"))
G=[]
print(("Enter the adjacency matrix for thw graph(enter 0 for no edge):"))
for i in range(N):
row=list(map(int,input().split()))
G.append(row)
return N,G
def prim_algorithm(N,G):
selected_node=[0]*N
no_edge=0
selected_node[0]=True
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]:
if minimum>G[m][n]:
minimum=G[m][n]
a=m

36
b=n
print(str(a)+"-"+str(b)+":"+str(G[a][b]))
selected_node[b]=True
no_edge+=1
N,G=get_user_input()
print("\n Minimum spanning tree using Prim's AlgorithM:")
prim_algorithm(N,G)

37
OUTPUT:

38
PROGRAM NO:8
AIM: Write a program that implements Kruskal’s algorithm to generate
minimum cost spanning Tree.
DATE: 7-12-23
DONE BY: ANUSHA K S
CLASS:III BCA

# Function to get user input for the graph


def get_user_input():
# Get the number of vertices in the graph
N = int(input("Enter the number of vertices in the graph: "))

# Initialize the list to store edges


edges = []

# Prompt the user to enter edges and weights


print("Enter the edges and weights for the graph (format: vertex1 vertex2 weight), input
'done' to finish:")

# Continue taking input until the user enters 'done'


while True:
edge_input = input().strip().lower()
if edge_input == 'done':
break
# Convert input to integers and append to the edges list
edges.append(tuple(map(int, edge_input.split())))

return N, edges

# Function to find the parent of a node in the disjoint set


def find_parent(parent, i):
# Recursive function to find the ultimate parent of a set

39
if parent[i] == i:
return i
return find_parent(parent, parent[i])

# Function to perform Kruskal's algorithm


def kruskal_algorithm(N, edges):
# Sort edges by weight in ascending order
edges = sorted(edges, key=lambda x: x[2])

# Initialize disjoint set with each vertex as its own parent


parent = list(range(N))

# Print the edges and weights


print("Edge : Weight\n")

# Iterate through sorted edges


for edge in edges:
u, v, weight = edge
set_u, set_v = find_parent(parent, u), find_parent(parent, v)

# Check if adding this edge creates a cycle


if set_u != set_v:
print(f"{u}-{v}:{weight}")
# Update the parent to merge the sets
parent[set_u] = set_v

# Get user input for the graph


N, edges = get_user_input()

# Perform Kruskal's algorithm and print the Minimum Spanning Tree

40
print("\nMinimum Spanning Tree using Kruskal's Algorithm:")
kruskal_algorithm(N, edges)

41
OUTPUT:

42

You might also like