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

ADA Lab Manual HD

Uploaded by

darjihemil4902
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views31 pages

ADA Lab Manual HD

Uploaded by

darjihemil4902
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

LAB

MANUAL

FOR

Analysis And Design of

Algorithms (3150703)

BE 5TH SEM

COMPUTER

ENGINEERING

NEOTECH INSTITUTE OF TECHNOLOGY


1
CERTIFICATE

This is to certify that Mr./Ms. …………………………………


with enrollment no. ………………………… has successfully
completed his/her laboratory experiments in the subject (with code)
…………………………………… from the department
of…………………. during the academic
year…………………

Date of Submission:………………. Staff in Charge:…………….

2
Index
Sr Title Of Experiment Page Date Sign
No. no.
1 Implementation & Time Analysis of
Sorting Algorithms

2 Implementation & Time Analysis of


Linear & Binary Search Algorithms

3 Implementation of Max Heap Algorithm

4 Implementation & Time Analysis of


factorial program using iterative &
recursive method
5 Implementation of knapsack
Problem using dynamic
programming
6 Implementation of Chain
Matrix Multiplication Using
Dynamic Programming
7 Implementation of Making a Change
Problem Using Dynamic Programming

8 Implementation of knapsack
Problem using Greedy
Algorithm
9 Implementation of Graph & Searching
(DFS & BFS)

10 Implementation Prim’s Algorithm


Hemil Darji 231173107001

PRACTICAL – 1
AIM :- Implementation and Time analysis of sorting algorithms. Bubble
sort, Selection sort, Insertion sort, Merge sort and Quick sort.
Bubble
sort:- Code:
# Bubble sort in Python

def bubbleSort(array):
for i in range(len(array)):
for j in range(0, len(array) - i -
1): if array[j] > array[j + 1]:
temp = array[j]
array[j] =
array[j+1]
array[j+1] = temp
data = [103, 24, 95, 125, 222, 191, 990]
bubbleSort(data)
print('Sorted Array
:') print(data)

Output:-

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

Selection
sort:- Code:
# Selection sort in Python

def selectionSort(array,
size): for step in
range(size):
min_idx = step
for i in range(step + 1, size):
if array[i] <
array[min_idx]: min_idx
=i
(array[step], array[min_idx]) = (array[min_idx], array[step])
data = [2, 45, 0, 11, 9]
size = len(data)
selectionSort(data,
size) print('Sorted
Array:') print(data)

Output:-

Insertion
sort:- Code:
3150703 Analysis and Design Algorithm
Hemil Darji 231173107001

# Insertion sort in Python

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

def insertionSort(array):
for step in range(1,
len(array)): key =
array[step]
j = step - 1
while j >= 0 and key <
array[j]: array[j + 1] =
array[j]
j=j-1
array[j + 1] =
key data = [9, 5, 1, 4,
3]
insertionSort(data)
print('Sorted
Array:') print(data)

Output:-

Merge
sort:- Code:
# Merge Sort in Python

def
mergeSort(array):
if len(array) > 1:
3150703 Analysis and Design Algorithm
Hemil Darji 231173107001

r=
len(array)//2 L
= array[:r]
M = array[r:]

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

mergeSort(L)
mergeSort(M
)i=j=k=0
while i < len(L) and j <
len(M): if L[i] < M[j]:
array[k] =
L[i] i += 1
else:
array[k] =
M[j] j += 1
k += 1
while i < len(L):
array[k] =
L[i] i += 1
k += 1
while j < len(M):
array[k] =
M[j] j += 1
k += 1
def printList(array):
for i in
range(len(array)):
print(array[i], end="
")
print()
if __name == ' main
': array = [6, 5,
12, 10, 9, 1]
mergeSort(array)
print("Sorted array is:

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

") printList(array)

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

Output:-

Quick
sort:- Code:
# Quick sort in Python

def partition(array, low, high):


pivot =
array[high] i =
low - 1
for j in range(low, high):
if array[j] <= pivot:
i=i+1
(array[i], array[j]) = (array[j], array[i])
(array[i + 1], array[high]) = (array[high], array[i +
1]) return i + 1
def quickSort(array, low,
high): if low < high:
pi = partition(array, low,
high) quickSort(array, low, pi
- 1) quickSort(array, pi + 1,
high)
data = [8, 7, 2, 1, 0, 9, 6]
3150703 Analysis and Design Algorithm
Hemil Darji 231173107001

print("Unsorted
Array:") print(data)

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

size = len(data)
quickSort(data, 0, size -
1) print('Sorted Array:')
print(data)

Output:-

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

PRACTICAL:-2
AIM:- Implementation & Time Analysis of Linear & Binary Search
Algorithms.
Linear
search:- Code:
# Linear Search in Python

def linearSearch(array, n, x):


# Going through array
sequencially for i in range(0, n):
if (array[i] ==
x): return i
return -1
array = [2, 4, 0, -1, 9]
x = -1
n = len(array)
result = linearSearch(array, n,
x) if(result == -1):
print("Element not
found") else:
print("Element found at index: ", result)

OUTPUT:-

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

Binary
search:-
Code:-
# Binary Search in python

def binarySearch(array, x, low,


high): while low <= high:
mid = low + (high -
low)//2 if x == array[mid]:
return mid
elif x >
array[mid]: low
= mid + 1
else:
high = mid - 1
return -1
array = [3, 4, 5, 6, 7, 8, 9]
x=4
result = binarySearch(array, x, 0, len(array)-1)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")

OUTPUT:-

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

PRACTICAL:-3
AIM:- Implementation of Max Heap Algorithm.
Code:
def heapify(arr, n,
i): largest = i
l=2*i+
1r=2*i
+2
if l < n and arr[i] <
arr[l]: largest = l
if r < n and arr[largest] <
arr[r]: largest = r
if largest != i:
(arr[i], arr[largest]) = (arr[largest],
arr[i]) heapify(arr, n, largest)
def
heapSort(arr)
: n = len(arr)
for i in range(n // 2, -1, -
1): heapify(arr, n, i)
for i in range(n - 1, 0, -1):
(arr[i], arr[0]) = (arr[0],
arr[i]) heapify(arr, i, 0)
arr = [12, 11, 13, 5, 6, 7, ]
heapSort(arr
) n = len(arr)
print('Sorted array
is') for i in range(n):
print(arr[i])

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

OUTPUT:-

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

PRACTICAL:-4
AIM:- Implementation & Time Analysis of factorial program using
iterative & recursive method.

Code:

# Factorial of a number using

recursion def recur_factorial(n):


if n == 1:
return
n
else:
return n*recur_factorial(n-
1) num = 7
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is
1") else:
print("The factorial of", num, "is", recur_factorial(num))

OUTPUT:-

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

PRACTICAL:-5
AIM:- Implementation of knapsack Problem using dynamic
programming. Code:-

# a dynamic approach
# Returns the maximum value that can be stored by the bag
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 w in range(W +
1): if i == 0 or w ==
0:
K[i][w] = 0
elif wt[i-1] <= w:
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w])
else:
K[i][w] = K[i-1][w]
return K[n][W]
val = [50,100,150,200]
wt = [8,16,32,40]
W = 64
n = len(val)
print(knapSack(W, wt, val,
n))

OUTPUT:-

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

PRACTICAL:-6
Aim:- Implementation of Chain Matrix Multiplication Using Dynamic
Programming.

Code:-
# Dynamic Programming Python implementation of Matrix
# Chain Multiplication.
import sys
def MatrixChainOrder(p, n):
m = [[0 for x in range(n)] for x in
range(n)] for i in range(1, n):
m[i][i] = 0
for L in range(2,
n):
for i in range(1, n-L +
1): j = i + L-1
m[i][j] =
sys.maxsize for k in
range(i, j):
q = m[i][k] + m[k + 1][j] + p[i-
1]*p[k]*p[j] if q < m[i][j]:
m[i][j] = q
return m[1][n-1]
arr = [1, 2, 3, 4, 3]
size = len(arr)
print("Minimum number of multiplications is " +
str(MatrixChainOrder(arr, size)))

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

Output:-

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

PRACTICAL:-7

Aim:- Implementation of Making a Change Problem Using Dynamic


Programming.

Code:-

# Dynamic Programming Python implementation of Coin


# Change problem
def count(S, m, n):
table = [[0 for x in range(m)] for x in
range(n+1)] for i in range(m):
table[0][i] = 1
for i in range(1, n+1):
for j in range(m):
x = table[i - S[j]][j] if i-S[j] >= 0 else 0
y = table[i][j-1] if j >= 1 else 0 table[i]
[j] = x + y
return table[n][m-
1] arr = [1, 2, 3]
m=
len(arr) n =
4
print(count(arr, m, n))

Output:-

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

PRACTICAL:-8
Aim:- Implementation of knapsack Problem using Greedy Algorithm.
Code:-

def fractional_knapsack(values, weights,


W): n = len(values)
# Calculate value/weight ratio for each item
ratios = [(values[i] / weights[i], values[i], weights[i]) for i in range(n)]
# Sort items based on ratio in non-increasing order
ratios.sort(reverse=True)
total_value = 0 # Initialize total value
current_weight = 0 # Initialize current weight
# Loop through all items
for ratio, value, weight in ratios:
if current_weight + weight <=
W: # Add entire item
total_value += value
current_weight +=
weight
else:
# Add fraction of item
fraction = (W - current_weight) /
weight total_value += value * fraction
break
return
total_value #
Example Usage
values1 = [60, 100, 120]
weights1 = [10, 20, 30]
W1 = 50
print("Maximum value in knapsack =", fractional_knapsack(values1, weights1,
3150703 Analysis and Design Algorithm
Hemil Darji 231173107001

W1))
values2 = [40, 100, 50, 60]

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

weights2 = [20, 10, 40, 30]


W2 = 50
print("Maximum value in knapsack =", fractional_knapsack(values2, weights2,
W2))

Output:-

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

PRACTICAL:-9
Aim:- Implementation of Graph & Searching (DFS &
BFS). DFS:-
Code:
# DFS algorithm in Python

def dfs(graph, start,


visited=None): if visited is
None:
visited = set()
visited.add(start
) print(start)
for next in graph[start] -
visited: dfs(graph, next,
visited)
return visited
graph = {'0': set(['1', '2']),
'1': set(['0', '3', '4']),
'2': set(['0']),
'3': set(['1']),
'4': set(['2', '3'])}
dfs(graph, '0')

Output:-

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

BFS:-
Code:
# BFS algorithm in Python

import collections
def bfs(graph,
root):
visited, queue = set(), collections.deque([root])
visited.add(root)
while queue:
# Dequeue a vertex from
queue vertex = queue.popleft()
print(str(vertex) + " ", end="")
# If not visited, mark it as visited,
and # enqueue it
for neighbour in
graph[vertex]: if neighbour
not in visited:
visited.add(neighbour)
queue.append(neighbour)
if __name == ' main ':
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1, 2]}
print("Following is Breadth First Traversal: ")
bfs(graph, 0)
int pop() {
return stack[top--];
}

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

Output:-

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

PRACTICAL:-10
Aim:- Implementation Prim’s Algorithm.
Code:-
# Prim's Algorithm in Python

INF = 9999999
V=5
G = [[0, 9, 75, 0, 0],
[9, 0, 95, 19, 42],
[75, 95, 0, 51, 66],
[0, 19, 51, 0, 31],
[0, 42, 66, 31, 0]]
selected = [0, 0, 0, 0, 0]
no_edge = 0
selected[0] =
True
print("Edge : Weight\
n") while (no_edge < V
- 1):
minimum =
INF x = 0
y=0
for i in range(V):
if selected[i]:
for j in range(V):
if ((not selected[j]) and G[i]
[j]): if minimum > G[i][j]:
minimum = G[i]
[j] x = i
y=j
3150703 Analysis and Design Algorithm
Hemil Darji 231173107001

print(str(x) + "-" + str(y) + ":" + str(G[x][y]))

3150703 Analysis and Design Algorithm


Hemil Darji 231173107001

selected[y] =
True no_edge +=
1

Output:-

3150703 Analysis and Design Algorithm

You might also like