Академический Документы
Профессиональный Документы
Культура Документы
DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING
IV SEM - 07CS46
Page No
1. Instructions 2
2. Question Bank 4
3. Viva-voce Questions 6
4. Introduction to vi Editor 11
5. Lab Schedule 13
6. Algorithms 14
2
INSTRUCTIONS
General Instructions:
2. Break-up of marks:
Viva = 02
_____________
10
_____________
3
lab slot.
Minimum three sets of input along with expected output for
each program.
4
QUESTION BANK
5
b) Vertices deletion method.
10. Write a program to sort a given set of elements using Quick sort
method.
12. Write a program to print all the nodes reachable from a given
starting node in a
diagraph using Breadth First Search method.
14. Write a program to 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, then 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.
6
16. Write a program to find Minimum Cost Spanning Tree of a given
undirected graph using Prims algorithm.
17. a) Write a program to print all the nodes reachable from a given
starting node in a digraph using Depth First Search method.
b) Write a program to compute the transitive closure of a given
directed graph using Warshall’s algorithm.
VIVA-VOCE QUESTIONS
and ;
and ;
and ;
7
and .
p = 1;
for (i=0; i < 2*n; i++)
p = p*i;
9. Give a characterization, in big-Oh terms, of the following loop:
s = 0;
for (i=0; i < 2*n; i++)
for (j=0; j < i; j++)
s = s + i;
10. Give a characterization, in big-Oh terms, of the space complexity
of the following loop:
8
15. Suppose we are told the worst case complexity of an algorithm is
E A S Y Q U E S T I O N
21. Show how simple quick sort sorts the following keys:
10 14 12 28 15 23 15 24 28 15 26 30
What is the maximum stack size?
22. Show how natural merge sort sorts the keys: 3,5,1,4,7,2,8,3.
23. Explain why a minimum cost sub graph must be a tree.
24. Explain the following representations with respect to the
graphs shown in figure
i. adjacency matrix
ii. packed adjacency list
iii. linked adjacency list
9
2 1 2 1
3
1 3 4 2 4
5 4
5 3 5
10
1 9
2 3 4
6
5 7
1 2
3 4
8
6 5
7
11
38. Explain the merge sort and obtain its time and space
complexity.
39. What is a Huffman tree? Explain an algorithm to construct
the Huffman tree.
40. Explain the concept of decision trees for sorting algorithms.
41. Explain the Prim's algorithm to construct a minimum cost
spanning tree with respect to the following graph
1
6
2
7
5 3
v1 v2 v3 v4
V1 ∞ -5 3 8
V2 4 ∞ 6 5
V3 -2 8 ∞ 10
V4 8 13 14 ∞
12
Show the matrix after the edge (v3, v2) is selected and compute
the bound for the resulting matrix.
48. Briefly explain the concepts of polynomial reducibility and NP-
completeness.
49. Suggest a high level algorithm to solve a 0/1 Knapsack
problem using backtracking.
50. Explain Strassen's matrix multiplication method.
INTRODUCTION TO VI EDITOR
13
a append new text after the cursor.
o start to edit a new line after the current one.
O start to edit a new line before the current one.
Replacing characters, lines and words
replace the current character (does not enter edit
r mode).
enter edit mode and substitute the current character
s by several ones
cw enter edit mode and change the word after the cursor.
enter edit mode and change the rest of the line after
C the cursor.
Copying and pasting
yy copy (yank) the current line to the copy/paste buffer.
p paste the copy/paste buffer after the current line.
P Paste the copy/paste buffer before the current line.
Deleting characters, words and lines
x delete the character at the cursor location.
dw delete the current word.
D delete the remainder of the line after the cursor
dd delete the current line.
Repeating commands
. repeat the last insertion, replacement or delete command.
Looking for
strings
/string find the first occurrence of string after the cursor.
?string find the first occurrence of string before the cursor.
n find the next occurrence in the last search.
Replacing strings
n,ps/str1/str2/g between line numbers n and p, substitute all (g:global)
occurrences of str1 by str2.
1,$s/str1/str2/g g in the whole file ($: last line), substitute all occurrences
of str1 by str2.
Misc
[Ctrl] l redraw the screen.
J join the current line with the next one
Exiting and
saving
ZZ save current file and exit vi.
:w write (save) to the current file.
:w file write (save) to the file file
:wq quit vi after saving the changes.
14
:q! quit vi without saving changes.
Applying a command several times - Examples
5j move the cursor 5 lines down.
30dd delete 30 lines
4cw change 4 words from the cursor.
1G go to the first line in the file.
LAB SCHEDULE
Lab Programs to be
Session completed
1 Introduction
2 1,5
3 3, 10
4 7, 4
5 17 (a), 6
6 2, 15(b)
15
7 8, 13
8 17(b), 12
9 11, 15(a)
10 16, 9
11 14, 18
ALGORITHMS
Linear Search
Binary Search
17
Complexity: The Complexity is analyzed using Masters Theorem. The
complexity depends on the size and type of input.
1. Best Case: Ω (1)
2. Worst Case: Ө (log n)
3. Average Case: Ө (log n)
Linear Search
Best Case Worst Case
Experimen Theoretic Experimen Theoretic
Size tal al tal al
100
200
400
800
160
0
320
0
Binary Search
Best Case Worst Case
Siz Experimen Theoretic Experimen Theoretic
e tal al tal al
100
200
400
800
160
0
320
0
18
As a result, the array elements are eliminated in
decreasing order. Under the array implementation of heaps, an
element being deleted is placed last, the resulting array will be
exactly the original array sorted in ascending order.
19
1024
2048
4096
8192
MergeSort (B [0…└n/2┘-1])
┌ ┐
MergeSort (C [0… n/2 -1])
Merge (B, C, A)
20
Algorithm: Merge (B [0…p-1], C [0...q-1], A [0...p+q-1])
//Merges two sorted arrays into one sorted array.
//Input: Arrays B [0…p-1] and C [0...q-1] both sorted.
//Output: Sorted array A [0...p+q-1] of the elements of B and C.
{
i ← 0; j←0; k←0
while i<p and j<q do
{
if B[i] <= C[j]
A[k] ← B[i]; i← i+1
else
A[k] ← C[j]; j← j+1
k ← k+1
}
if i=p
copy C [j…q-1] to A[k…p+q-1]
else
copy B [i…p-1] to A[k…p+q-1]
}
Complexity:
Note: Program to be executed for various sizes of input. Fill the given
table where g(n)= n log n. Obtaining a constant value in the column
t(n)/g(n) would prove that the complexity of merge sort is n log n.
21
4. Write a program to check whether a given graph is
connected or not using DFS method.
Algorithm: GraphConnectivity( G)
// Checks for connectivity of a Graph using DFS
//Input: Graph G = (V, E)
//Output: Returns true for a connected graph, false otherwise.
//visited [] is global
{
n ← |V|
for i←0 to n do
visited [i] ← 0
DFS (v) // any arbitrary vertex v
for i ← 0 to n do
if ( visited [i] = 0 )
return false
return true
}
22
graph’s vertices and edges respectively.
Selection sort works by scanning the entire given list to find its
smallest element and exchange it with the first element, putting the
smallest element in its final position in the sorted list. Then we can
scan the list, starting with the second element, to find the smallest
among the last n-1elements and exchange it with the second element,
putting the second smallest element in its final position. On the ith
pass through the list, which we number from 0 to n-2, the algorithm
searches for the smallest item among the last n-1 elements and swaps
it with Ai. After n-1 passes, the list is sorted.
Note: Program to be executed for various sizes of input. Fill the below
table where g(n)=n2. Obtaining a constant value in the column
t(n)/g(n) would prove that the complexity of selection sort for all cases
is Ө(n2).
23
512
1024
2048
4096
8192
Algorithm: TopologicalSorting ()
// algorithm to print the toplogical ordering of a graph
L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edges
while S is non-empty do
remove a node n from S
insert n into L
for each node m with an edge e from n to m do
remove edge e from the graph
if m has no other incoming edges then
insert m into S
if graph has edges then
output error message (graph has at least one cycle)
else
output message (proposed topologically sorted order: L)
25
Complexity: The algorithms for topological sorting have running time
linear in the number of nodes plus the number of edges O(|V|+|E|).
26
table where g1(n)=n and g2(n)=n2. Obtaining a constant value in the
column t(n)/g(n) would prove that the complexity of insertion sort for
all cases.
• Constraint: ∑w
i∈T
i ≤W
“knapsack”
Items: Solution:
5 (2 in)
1 2 3 4 5 3 (2 in)
1 (4 in)
Weight: 4 in 2 in 2 in 6 in 2 in
Algorithm: 0/1Knapsack(S, W) 9 in
of items$3
//Input: set S$20
Benefit: $6 b$25
with benefit $80 wi; max. weight W
i and weight
//Output: benefit of best subset with weight at most W
// Sk: Set of items numbered 1 to k.
//Define B[k,w] = best selection from Sk with weight exactly equal to w
{
for w ← 0 to n-1 do
B[w] ← 0
for k ← 1 to n do
{
for w ← W downto wk do
{
if B[w-wk]+bk > B[w] then
B[w] ← B[w-wk]+bk
} 27
}
}
Complexity: The Time efficiency and Space efficiency of 0/1 Knapsack
algorithm is Ө(nW).
Algorithm : Partition(A[l..r])
//Partition a subarray by using its first element as its pivot
//Input:A subarray A[l..r] of A[0..n-1],defined by its left and right indices l and r (l<r)
//Output:A partition of A[l..r],with the split position returned as this function’s value
{
p ← A[l]
i ← l; j ← r+1
repeat
{ repeat i ← i+1 until A[i] >=p
repeat j ← j-1 until A[j] <=p
swap(A[i],A[j])
} until i>=j
swap(A[i],A[j]) // undo last swap when i>=j
swap(A[l],A[j]) 29
return j
}
Complexity: Cbest (n) =2 Cbest (n/2) +n for n>1 Cbest (1) =0
Cworst (n) ∈ θ (n2)
Cavg (n) ≈ 1.38nlog2n
Note: Program to be executed for various sizes of input. Fill the below
table where g1(n)=n2 and g2(n)=n log n. Obtaining a constant value in
the column t(n)/g(n) would prove that the complexity of quick sort for
all cases.
30
11. Write a program to find Minimum cost spanning tree of a
given undirected graph using Kruskal’s algorithm.
Algorithm : BFS(G)
//Implements a breadth-first search traversal of a given graph
//Input: Graph G = (V, E)
//Output: Graph G with its vertices marked with consecutive integers in the order they
//have been visited by the BFS traversal
{
mark each vertex with 0 as a mark of being “unvisited”
count ←0
for each vertex v in V do
{
if v is marked with 0
12. Write a program bfs(v) to print all the nodes reachable from a
given} starting node in a diagraph using Breadth First Search
}method.
BFSAlgorithm
explores : bfs(v)
graph moving across to all the neighbors of last visited
//visits all
vertex traversalsthe unvisited
i.e., vertices connected
it proceeds in atoconcentric
vertex v andmanner
assigns them
by the numbers
visiting all
//in order they are visited via global variable count
the vertices that are adjacent to a starting vertex, then all unvisited
{
vertices two edges apart from it and so on, until all the vertices in the
count ← count
same connected +1
component as the starting vertex are visited. Instead
mark v with
of a stack, BFS uses queue. count and initialize queue with v
while queue is not empty do
{
a := front of queue
for each vertex w adjacent to a do
{
if w is marked with 0
{
count ← count + 1
mark w with count
add w to the end of the queue
}
}
remove a from the front of32the queue
}
}
Complexity: BFS has the same efficiency as DFS: it is Θ (V2) for
Adjacency matrix representation and Θ (V+E) for Adjacency linked list
representation.
13. Write a program to implement all pair shortest paths
problem using Floyd’s
algorithm.
33
Algorithm Floyd(W[1..n,1..n])
//Implements Floyd’s algorithm for the all-pairs shortest paths problem
//Input: The weight matrix W of a graph
//Output: The distance matrix of shortest paths length
{
D←W
for k←1 to n do
{
for i ← 1 to n do
{
for j ← 1 to n do
{
D[i,j] ← min (D[i, j], D[i, k]+D[k, j] )
}
}
}
return D
}
34
applying backtracking algorithm, the solutions could be obtained.
Some instances of the problem may have no solutions.
Algorithm SumOfSub(s, k, r)
//Find all subsets of w[1…n] that sum to m. The values of x[j], 1<= j < k, have
n
already //been determined. s=∑k-1 w[j]*x[j] and r =∑ w[j]. The w[j]’s are in ascending
order.
j=1 j=k
{
x[k] ← 1 //generate left child
if (s+w[k] = m)
write (x[1...n]) //subset found
else if ( s + w[k]+w[k+1] <= m)
SumOfSub( s + w[k], k+1, r-w[k])
//Generate right child
if( (s + r - w[k] >= m) and (s + w[k+1] <= m) )
{
x[k] ← 0
SumOfSub( s, k+1, r-w[k] )
}
}
Horspool algorithm
35
Step1: For a given pattern of length m and the alphabet used in both
the pattern and text, construct the shift table.
Step 2: Align the pattern against the beginning of text
Step 3 Repeat the following until either a matching substring is found
or the pattern reaches beyond the last character of text. Starting
with the last character in the pattern, compare the corresponding
characters in the pattern and text until either all m characters are
matched or a mismatching pair is encountered. In the latter case,
retrieve the entry t(c) from the c’s column of the shift table where
c is the text character currently aligned against the last character
of the pattern and shift the pattern by t(c) characters to the right
along the text.
The algorithm for computing shift table entries. Initialize all the entries
to the pattern’s length m and scan the pattern left to right repeating
the following step m-1 times, for the jth character of the
pattern(0<=j<=m-2).
Algorithm Shift Table (P [0...m-1])
//Fills the shift table used by Horspool’s algorithm
//Input: Pattern P[0..m-1] and an alphabet of possible characters
//Output: Table [0...size-1] indexed by the alphabet’s characters
//and filled with shift sizes
{
initialize all the elements of Table with m
for j ←0 to m-2 do Table[P[j]]36 ← m-1-j
return Table
}
Complexity: The worst case efficiency of Horspool algorithm is Θ
(nm). But for random texts, it is in Θ (n).
Computing a Binomial coefficient
Computing a Binomial coefficient is a standard example of applying
dynamic programming. Of the numerous properties of binomial co-
efficient, we concentrate on two:
1) C(n,k)=C(n-1,k-1)+C(n-1,k) for n>k>0
2) C(n,0)=C(n,n)=1
Algorithm Binomial(n,k)
// Computes C (n, k) by the dynamic programming algorithm
//Input: A pair of non negative integers n>=k>=0
//Output: The value of C (n, k)
{
for i← 0 to n do
{
for j ← 0 to min(i, k)do
{
if j=0 or j=k
C[i,j] ←1
else
C[i,j] ← C[i-1,j-1]+ C[i-1,j]
}
}
return C[n,k]
}
37
b) Write a program to compute the transitive closure of a
given directed graph using Warshall’s algorithm.
Algorithm : DFS(G)
//Implements a depth-first search traversal of a given graph
//Input : Graph G = (V,E)
//Output : Graph G with its vertices marked with consecutive integers in the order they
//have been first encountered by the DFS traversal
{
mark each vertex in V with 0 as a mark of being “unvisited”.
count ← 0
for each vertex v in V do
if v is marked with 0
dfs(v)
}
Algorithm : dfs(v)
//visits recursively all the unvisited vertices connected to vertex v by a path
//and numbers them in the order they are encountered via global variable count
{
count ← count+1
mark v with count
for each vertex w in V adjacent to v do
if w is marked with 0
dfs(w)
}
38
Warshall’s algorithm:
Algorithm Warshall(A[1..n,1..n])
//Implements Warshall‘s algorithm for computing the transitive closure
//Input: The Adjacency matrix A of a digraph with n vertices
//Output: The transitive closure of digraph
{
R(0) ← A
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]
}
}
}
return R(n)
}
39
18. Write a program to implement N Queen’s problem using
back tracking.
Algorithm Place( k, i)
//Returns true if a queen can be placed in kth row and ith column. Otherwise it
//returns false. x[] is a global array whose first (k-1) values have been set.
Abs(r) //returns the absolute value of r.
{
for j ← 1 to k-1 do
{
if ( (x[j]=i or Abs(x[j]-i) = Abs(j-k) )
{
return false
} 40
}
}
Complexity: Because the power of the set of all possible solutions of
the n queen’s problem is n! and the bounding function takes a linear
amount of time to calculate, the running time of the n queens problem
is O (n!).
41