Algorithm Units Notes
Algorithm Units Notes
Summary: This method divides the problem into smaller subproblems, solves each recursively, and
Examples: Binary Search, Merge Sort, Quick Sort, Strassens Matrix Multiplication
Pseudocode:
BinarySearch(arr, key):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == key:
return mid
else if arr[mid] < key:
low = mid + 1
else:
high = mid - 1
return -1
Summary: Greedy algorithms make the locally optimal choice at each step in hope of finding the
global optimum.
Examples: Huffman Coding, Kruskals and Prims MST, Job Scheduling, Fractional Knapsack
Pseudocode:
GreedyKnapsack(wt[], val[], W):
for i in 0 to n:
ratio[i] = val[i] / wt[i]
sort items by ratio
for item in sorted list:
if item can fit:
take full item
else:
take fraction
Subsequence
Pseudocode:
Knapsack(wt[], val[], W, n):
dp = array[n+1][W+1]
for i from 0 to n:
for w from 0 to W:
if i==0 or w==0:
dp[i][w] = 0
else if wt[i-1] <= w:
dp[i][w] = max(val[i-1] + dp[i-1][w - wt[i-1]], dp[i-1][w])
else:
dp[i][w] = dp[i-1][w]
return dp[n][W]
Summary: Backtracking solves problems incrementally and abandons solutions when not viable.
Examples: 8 Queens Problem, Graph Coloring, Hamiltonian Cycle, Travelling Salesman Problem
Pseudocode:
SolveNQueens(board, row):
if row >= N:
print(board)
return
for col in 0 to N:
if isSafe(board, row, col):
board[row][col] = 1
SolveNQueens(board, row + 1)
board[row][col] = 0
Examples: Subset Sum Problem, Vertex Cover, Travelling Salesman (approx), Data Stream
Algorithms
Pseudocode:
ApproxVertexCover(graph):
cover = set()
while E is not empty:
select (u, v) from E
add u and v to cover
remove all edges incident to u or v
return cover