Professional Documents
Culture Documents
Ada Sumission Adib
Ada Sumission Adib
Ada Sumission Adib
BubbleSort:
def bubbleSort(arr):
n = len(arr)
# optimize code, so if the array is already sorted, it doesn't need
# to go through the entire process
swapped = False
# Traverse through all array elements
for i in range(n-1):
# range(n) also work but outer loop will
# repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n-i-1):
if not swapped:
# if we haven't needed to make a single swap, we
# can just exit the main loop.
return
bubbleSort(arr)
Output:
def insertion_sort(list1):
value = list1[i]
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
size = len(data)
quickSort(data, 0, size - 1)
Output:
LinearSearch:
import random
import time
random.seed(42)
def linearSearch(array, n, x):
start = time.time()
index = linearSearch(arr, len(arr),27978215)
print(f"found element at {index}")
end = time.time()
print("took", end-start, "milliseconds")
Output:
if array[mid] == x:
return mid
else:
high = mid - 1
return -1
Output:
Code:
def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
if largest != i:
(arr[i], arr[largest]) = (arr[largest], arr[i]) # swap
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
Output:
Iterative method:
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
num = 5
print("Factorial of",num,"is",
factorial(num))
Output:
def factorial(n):
return 1 if (n==1 or n==0) else n * factorial(n - 1)
num = 5
print ("Factorial of",num,"is",
factorial(num)
Output:
Code:
else:
return max(
val[n-1] + knapSack(
W-wt[n-1], wt, val, n-1),
knapSack(W, wt, val, n-1))
if __name__ == '__main__':
profit = [60, 100, 120]
weight = [10, 20, 30]
W = 50
n = len(profit)
print(knapSack(W, weight, profit, n))
Code:
import sys
def MatrixChainOrder(p, i, j):
if i == j:
return 0
_min = sys.maxsize
count = (MatrixChainOrder(p, i, k)
+ MatrixChainOrder(p, k + 1, j)
+ p[i-1] * p[k] * p[j])
if __name__ == '__main__':
arr = [1, 2, 3, 4, 3]
N = len(arr)
Code:
ways[0] = 1;
for i in range(len(Coins)):
if (Coins[i] <= j):
ways[j] += ways[(int)(j - Coins[i])];
return ways[N];
def printArray(coins):
for i in coins:
print(i);
if __name__ == '__main__':
Coins = [1, 5, 10];
print("Solution:",end="");
print(getNumberOfWays(12, Coins));
Code:
class Item:
def __init__(self, profit, weight):
self.profit = profit
self.weight = weight
if item.weight <= W:
W -= item.weight
finalvalue += item.profit
else:
finalvalue += item.profit * W / item.weight
break
return finalvalue
if __name__ == "__main__":
W = 50
arr = [Item(60, 10), Item(100, 20), Item(120, 30)]
max_val = fractionalKnapsack(W, arr)
print(max_val)
DFS:
from collections import defaultdict as dd
class Graph:
def __init__(self):
self.graph = dd(list)
queue = []
visited_vertices[n] = True
queue.append(n)
while queue:
n = queue.pop(0)
print (n, end = " ")
for v in self.graph[ n ]:
if visited_vertices[v] == False:
queue.append(v)
visited_vertices[v] = True
print ( " The Breadth First Search Traversal for The Graph is as Follows: " )
graph.BFSearch(3)
Output:
if __name__ == "__main__":
# Graph of nodes
graph = {
0: [2],
1: [2, 3],
2: [0, 1, 4],
3: [1, 4],
4: [2, 3]
}
node = 0 # Starting node
visited = [False]*len(graph) # Make all nodes to False initially
component = []
dfs(node, graph, visited, component) # Traverse to each node of a graph
print(f"Following is the Depth-first search: {component}") # Print the answer
Code:
import sys
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
def primMST(self):
self.printMST(parent)
if __name__ == '__main__':
g = Graph(5)
g.graph = [[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]
g.primMST()
Code:
class Graph:
else:
parent[y] = x
rank[x] += 1
def KruskalMST(self):
i=0
e=0
self.graph = sorted(self.graph,
key=lambda item: item[2])
parent = []
rank = []
u, v, w = self.graph[i]
i=i+1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e=e+1
result.append([u, v, w])
self.union(parent, rank, x, y)
if __name__ == '__main__':
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
# Function call
g.KruskalMST()
Output:
Code:
if m == 0 or n == 0:
return 0;
elif X[m-1] == Y[n-1]:
return 1 + lcs(X, Y, m-1, n-1);
else:
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
X = "AGGTAB"
Y = "GXTXAYB"
print ("Length of LCS is ", lcs(X, Y, len(X), len(Y)))
Output:
Code:
if (seq[i] == seq[j]):
return lps(seq, i + 1, j - 1) + 2
if __name__ == '__main__':
seq = "GEEKSFORGEEKS"
n = len(seq)
print("The length of the LPS is",
lps(seq, 0, n - 1))