Sie sind auf Seite 1von 20

33

Algorithms Lab Manual


33
V-Sem CSE

Problem 1: Perform (i) recursive binary search and (ii) linear search.
Hence, find the time required to search an element.

 Algorithm BinarySearch(A[0..n - 1], key, lo, hi)


// Input: An integer sorted array A[0..n – 1].
// Output: returns mid (if key found) or -1 (key not found)
if lo > hi
return -1 // key not found
mid ← (low + high)/2
if key = A[mid] return mid // key found
if key < A[mid]
return BinarySearch (A, n, key, lo, mid – 1)
else
return BinarySearch (A, n, key, mid + 1, hi)
end BinaySearch.

// RECURSIVE LINEAR SEARCH – TIME EFFICIENCY

 Algorithm LinearSearch(A[0..n - 1], n, key)


// Input: An integer array A[0..n – 1] and key to be searched.
// Output: returns position (if key found) or -1 (key not found)
if n < 0
return -1 // key not found

if A[n-1] = key return n // key found


else
return LinearSearch (A, n-1, key)
end LinearSearch.
2 BIT, CSE Department

Problem 2: Sort a given set of elements using heapsort method.

 Algorithm HeapSort(A[1..n], n)
// Input: Array A[1..n] of size n.
// Output: Sorted array A
Build_Max_Heap(A, n)
for i ← n downto 2 do
Exchange A[1] ↔ A[i]
Max_Heapify(A, 1, i - 1)
end HeapSort.
Algorithms Lab Manual 3

Problem 3: Write C++ program to sort a given set of elements using


Mergesort method.

 Algorithm MergeSort (A, low, high)


// Input: An n-element Array A[0..n – 1]
// Output: Sorted array A
if low < high // at least two elements
mid ← (low + high) / 2 // divide the list into two halves
MergeSort(A, low, mid)
MergeSort(A, mid + 1, high)
Merge(low, mid, high)
end MergeSort.

 Algorithm Merge(A[0..n – 1], low, mid, high)


// Input: Semi sorted Array A
// Output: Merged sorted array A from low to high
i ← h ← low // i is for the first sublist
j ← mid + 1 // j is for the second sublist
while h  mid and j  high do // sublists not exhausted yet
if A[h]  A[j]
B[i] ← A[h]
h←h+1
else
B[i] ← A[j]
j←j+1
i←i+1
if h > mid // first sublist exhausted – copy remaining elements.
for k ← j to high do
B[i] ← A[k]
i←i+1
k←k+1
else // second sublist exhausted - copy remaining elements.
for k ← h to mid do
B[i] ← A[k]
i←i+1
k←k+1
// Copy B to A
for k ← low to high do
A[k] ← B[k]
k←k+1
end Merge.
4 BIT, CSE Department

Problem 4: Write a C++ program for DFS. Using this display all the strongly
connected components.

 Algorithm dfs(G, v)
// Input: A Graph, G and starting vertex v
// Output: DFS tree
visited[v] ← 1 // mark v as visited
for each vertex w adjacent to v do
if visited[w] = 0 // vertex not yet visited
dfs(G, w) // continue to explore
end dfs.

 Algorithm DFS_Visit_All(G)
// Input: G{V, E}
// Output: DFS spanning tree or forest
for each vertex v  V do
visited[v] ← 0 // mark all vertices as unvisited
for each vertex v  V do
if visited[v] = 0
dfs(G, v)
end DFS_Visit_All.
Algorithms Lab Manual 5

Problem 5: Sort a given set of elements using selection sort.

 Algorithm SelectionSort(A[0..n – 1], n)


// Input: Array of numbers, A
// Output: Sorted Array A
for i ←0 to n – 2 do
min ← i
for j ← (i + 1) to (n – 1) do
if (A[j] < A[min]) min ← j
// Swap A[i] ↔ A[min]
temp ← A[i]
A[i] ← A[min]
A[min] ← temp
end SelectionSort.
6 BIT, CSE Department

Problem 6: Obtain the topological ordering of vertices in a given


digraph

 Algorithm topSortDFS(G)
// Input: A Graph, G
// Output: Topological sorting order
Initialize array visited by setting all entries to white.
Initialize linked list L
for all v  V do
if visited[v] = white
DFSSort(G, v)
print all vertices in L
end topSortDFS.

 Algorithm DFSSort(G, v)
// Input: A Graph, G and starting vertex v
// Output: Add vertices in L
visited[v] ← grey
for all w adjacent to v do
if visited[w] = white
DFSSort(G, w)
else if visited[w] = grey
print “G has a cycle”
stop.
visited[v] ← black
L.insertFirst(v)
end DFSSort.
Algorithms Lab Manual 7

Problem 7: Write a C++ program to simulate insertion sort.

 Algorithm InsertionSort(A[0..n-1], n)
// Input: An array A[0..n – 1]
// Output: Sorted array A
for j ← 1 to n – 1 do
k ← A[j]
i←j–1
while i  0 and k < A[i] do
A[i + 1] ← A[i]
i←i–1
A[i + 1] ← k
end InsertionSort.
8 BIT, CSE Department

Problem 8: Implement 0/1 knapsack problem using dynamic


programming.

 Algorithm MFK(i, j)
// Input: Number of objects and maximum weight of Knapsack
// Output: Solution vector (0/1), V
if V[i, j] = –1
if j < Weights[i]
p ← MFK(i – 1, j) // exclude object i
else // include object i
p ← Max(MFK(i – 1, j), Profits[i] + MFK(i – 1, j – Weights[i])
V[i, j] ← p
return V[i, j]
end MFK.
Algorithms Lab Manual 9

Problem 9: Form a given vertex in a weighted connected graph, find


the shortest paths to other vertices using Dijkstra's algorithm.

 Algorithm Dijkstras(G, s)
// Input: Weighted Graph (directed/undirected) and a stating vertex s
// Output: Shortest path from s to all other vertices, i.e. d[1..n]
for each v ≠ s do // Initialize_Single_Source(V, s)
d[v] ← 
d[s] ← 0
S← ø
Q ← V[G] // priority queue contain all vertices of G
while Q ≠ ø do // using the d labels as keys
u ← Extract_Min(Q)
S ← S  {u}
for each vertex v adjacent to u and v  S do
if d[u] + w(u, v) < d[v] // Relax(u, v, w)
d[v] ← d[u] + w(u, v)
return d.
end Digkstras.
10 BIT, CSE Department

Problem 10: Sort a given set of elements using Quicksort method.

 Algorithm QuickSort(A[0..n – 1], i, j)


// Input: Array of numbers A[0..n – 1]
// Output: Sorted array A
// i, j: lower and upper bounds of a subarray
if i < j
// partition the given list into two segments
q ← Partition(A, i, j)
QuickSort(A, i, q) // sort Subarray 1
QuickSort(A, q + 1, j) // sort Subarray 2
end QuickSort.

 Algorithm Partition(A[p..r], p, r)
// Input: Array A, p and r: lower and upper bounds of the array
// Output: Position for swap with pivot
pivot ← A[p]
i←p
j←r+1
while true do
do i = i + 1 while A[i] < pivot
do j = j – 1 while A[j] > pivot
if i < j
Swap(A[i], A[j]) // A[i] ↔ A[i]
else
return j
end Partition.
Algorithms Lab Manual 11

Problem 11: Find minimum cost spanning tree of a given undirected


graph using Kruskal's algorithm.

 Algorithm Kruskals(G)
// Input: Undirected graph , G
// Output: Minimum Spanning Tree, T
T←
Ecount ← |V| - 1
while T  n - 1 and Ecount  0 do
// assuming that edges are stored in a min heap
Get the mincost edge from E and call it as (u, v)
if (u, v) does not form a cycle
T ← T  (u, v) // add (u, v) in T
Delete (u, v) from min heap
Ecount = Ecount – 1
return T
end Kruskals.
12 BIT, CSE Department

Problem 12: Write a C++ program to simulate the working of BFS.

 Algorithm bfs(G, v)
// Input: Graph with V vertices and E edges
// Output: BFS tree
// visited[0..V] is a Boolean array
visited[v] ← 1
Q.enqueue(v)
while not Q.isEmpty() do
v ← Q.dequeue()
for all w adjacent to v do
if visited[w] = 0
visited[w] = 1
Q.enqueue(w)
end bfs.

Fig. 6.13 Algorithm for BFS for a given v

 Algorithm bfs_Visit_All(G)
// Input: A Graph G = (V, E)
// Output: BFS Tree
for each vertex v  V do
visited[v] ← 0
Initialize Queue Q
for all v  V do
if visited[v] = 0
bfs(G, v)
end bfs_Visit_All.
Algorithms Lab Manual 13

Problem 13: Implement all pairs shortest path problem using Floyd's
algorithm.

 Algorithm Floyd(G)
// Input: Directed Weighted Graph, G (Cost Adjacency Matrix)
// Output: All pairs shortest path of G.
A←C
for k ← 1 to n do
for i ← 1 to n do
for j ← 1 to n do
A[i, j] ← min{A[i, j], A[i, k] + A[k, j]}
return A
end Floyd.
14 BIT, CSE Department

Problem 14: Find a subset of a given set S = (s1, 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}. A
suitable message is to be displayed if the given problem instance doesn't
have a solution.

 Algorithm SumofSub(s, k, r)
// Input: Set of n numbers, S[1..n]
// Output: Solution vector, Boolean vector: X[1..n]

// Create left child (with kth element) – refer to Fig. 11.8


X[k] ← 1
if (s + S[k]) = d
for i ← 1 to k do
if X[i] = 1
print S[i]
else
if s + S[k] + S[k + 1]  d
SumofSub (s + S[k], k + 1, r – S[k])
// Create right child (without kth object) – refer to Fig. 11.8
if (s + r – S[k]  d) and (s + S[k + 1]  d)
X[k] ← 0
SumofSub(s, k + 1, r – S[k])
end SumofSub.
Algorithms Lab Manual 15

Problem 15: Implement Horspool algorithm for string matching.

 Algorithm ShiftTable(P[0..m - 1])


// Input: Pattern Array P[0..m – 1]
// Output: Shift Table T[0..asize – 1]
for j ←0 to asize - 1 do
T[j] ← m //Initialize all elements of T [0..255] with m.
for j ← 0 to m - 2 do
T[P[j]] ← m – 1 – j // last char of pattern must be set to m
end ShiftTable.

 Algorithm Horspool(S[0..n - 1], P[0..m – 1])


// Input: Source string S[0..n – 1] and pattern string P[0..m – 1]
// Output: index of pattern in source, if found - otherwise -1
ShiftTable(P)
i←m–1
while i  n – 1 do
k←0
while k  m – 1 and P[m – 1 – k] = S[i – k] do
k←k+1
if k = m
return i – m + 1 // position of pattern in source
else i ← i + T[S[i]] // shift the pattern right of source
return –1 // pattern not in source
end Horspool.
16 BIT, CSE Department

Problem 16: Find the binomial coefficient using dynamic programming.

 Algorithm BC(n, k)
// Input: Integer numbers n and k.
// Output: Binomial Co-efficient of n and k
for i ← 0 to n do
C[i, 0] ← 1 // fill the first column
C[i, i] ← 1 // fill the diagonal elements
for i ←2 to n do
for j ← 1 to i-1 do
C[i, j] ← C[i – 1, j – 1] + C[i – 1, j]
return C[n, k]
end BC.
Algorithms Lab Manual 17

Problem 17: Find the minimum cost spanning tree of a given undirected
graph using Prim's algorithm.

 Algorithm Prim(G)
// Input: Directed, weighted graph, G
// Output: Minimum Spanning Tree, T
T←
U ← {1} // consider vertex 1 as starting vertex
while U ≠ V do
let (u, v) be the lowest cost edge such that
u  U and v  V - U
T ← T  {(u, v)} // add edge to spanning tree
U ← U  {v}
return T
end Prim.
18 BIT, CSE Department

Problem 18: Compute the transitive closure of a given directed graph


using Warshall's algorithm.

 Algorithm Warshall(G)
// Input: Directed graph, G
// Output: Transitive Closure, R
R(0) ← A // initialize R with adjacency matrix of G
for k ← 1 to n do
for i ← 1 to n do
for j ← 1 to n do
R(k)[i, j] ← R(k–1)[i, j] or (R(k–1)[i, k] and R(k–1) [k, j])
(n)
return R
end Warshall.
Algorithms Lab Manual 19

Problem 19: Implement the n–Queens problem using backtracking


method.
20 BIT, CSE Department

Problem 20: Write a C++ program to compute the mode of a given set of
numbers.

 Algorithm Mode(A[0..n-1])
// Input: Array A of size n.
// Output: Mode of A
highest ← 0
mode ← 0
for i ← 0 to MAX do
array2[i] ← 0
for i ← 0 to n do
array2[a[i]] ← array2[a[i]] + 1
// compute the largest
for i ← 0 to MAX do
if array2[i] > highest
highest ← array2[i]
mode ← i
return mode
end Mode.

Das könnte Ihnen auch gefallen