Sie sind auf Seite 1von 10

KU ASSIGNMENT 4TH SEM: TB 41 ALGORITHMS

PART A
I. Say whether the following statements are true or false.
1) Definiteness is one of the properties of an algorithm.
Ans:- TRUE
2) Graph is a linear data structure.
Ans :- FALSE
3) A tree is a connected graph.
Ans:- TRUE
4) The data structure used by recursion is stack.
Ans :- TRUE
5) Queue works on the strategy First in First out.
Ans :- TRUE
II. Using suitable word or phrase fill up the blanks in the following sentences:
1) _____________is the process of executing a correct program on data sets and
measuring the time and space.
Ans:- PROFILING
2) Tree is a_____________data structure.
Ans:-NON-LINEAR
3) For a graph with n? number of nodes the number of edges to form a tree is
_____________
Ans: n-1
4) Last in First out Data structure is referred to as _____________
Ans :- Stacks
5) A binary tree of depth K? has maximum of_____________number of
nodes.
Ans : 2k-1nodes,k>= 0
6) A _____________is a graph without self loop and parallel edges.
Ans. SIMPLE GRAPH
7) The two methods of searching are_____________and_____________
Ans.:- SEQUENTIAL SEARCH AND BINARY SEARCH
III. Write brief answers to the following questions:
1) Define algorithm. What are its properties?
Ans :- An algorithm is a set of instructions that provide step-by-step specifications to perform a task.
Ex:Step by step procedure for display 10 natural numbers:1. Set the value of counter to 1
2. Display counter

3. Increment counter by 1
4. If counter <= 10, go to step 2
The preceding step -by -step procedure is an algorithm because it produces the correct result in
A finite number of steps.
The properties of an algorithm are:
? Input: Specifies the data set that is applied to the algorithm to check its validity.
? Output: Specifies the data set that is produced as a result of the algorithm execution.
? Definiteness: Specifies that the instructions described in the algorithm should be well defined and
should not create any ambiguity.
? Termination: Specifies that the instructions described in the algorithm must contain a proper
termination condition.
? Effectiveness: Specifies that the algorithm take less time and less memory space during its
execution.
2) Give atleast four real life examples where we use stack operations.
Ans:- The real life examples of stacks are:
? Bangles in a hand: The bangles wore in a hand follow last-in-first-out (LIFO) strategy of stack. The
bangle that you wear first is the last one to be taken out while removing all the bangles from the
hand. The bangle that is worn last is the first one to be taken out.
? Same circumference circular rings in a pole: The rings having same circumference placed into a
pole also follow LIFO strategy. The topmost ring, which was the last to be placed in the pole, is the
first one to be taken out.
? The bolts screwed to a single nut: When the bolts are screwed to a single nut, the last screwed bolt
is unscrewed first and the bolt that was screwed first is unscrewed in the last.
? Battery cells in a torch: The battery cells in a torch also follow the same LIFO strategy of stack.
3) Differentiate full and complete binary trees.
Ans:- The following table lists the differences between complete binary trees and full binary trees:
Complete binary trees Full binary trees
All the nodes at the previous level are fully accommodated before the next level is accommodated.
All levels are maximally accommodated.
Number of nodes at the last (n) level may or may not equal to 2n.
Number of nodes at the last (n) level is exactly equal to 2n.
Leaf nodes may or may not be at the same level.
All leaf nodes are at the same level.
A complete binary tree may or may not be full binary tree.
A full binary tree is always a complete binary tree.
4) What are the demerits of recursion?
Ans:- Demerits of recursion are:
Many programming languages do not support recursion; hence, recursive mathematical function is
implemented using iterative methods.

Even though mathematical functions can be easily implemented using recursion, it is always at the
cost of execution time and memory space.
The recursive programs take considerably more storage and take more time during processing.
PART B
1. a) What are the characteristics of an algorithm? Describe with an example.
Ans:- There are five Characteristics of every Algorithm: 1) INPUT
2) OUTPUT
3) DEFINITENESS
4) Effectiveness
5) Termination
Therefore, an algorithm can be defined as a sequence of definite and effective instructions, which
terminates with the production of correct output from the given input.
For EXAMPLE:- try to present the scenario of a man brushing his own teeth as an algorithm as
follows :1). Take the brush
2). Apply the paste
3). Start brushing
4). Rinse
5). Wash
6). Stop
If one goes through these 6 steps without being aware of the statement of the problem, he could
possibly feel that this is the algorithmfor claning a toilet. This is because of several ambiguities while
comprehending every step. Step-1 may imply tooth brush,paint brush, toilet brush, etc. uch an
algorithm arises from the instruction of the above algorithm step.thus every step has to be made
unambiguous.An unambiguous step is called definite instruction.
b) Write an algorithm to implement any three operations of a queue.
Ans:- Algorithm: Isempty
Input: Q, Queue
Output: Boolean
Method:
If (F==0)
Return (yes)
Else
Return (no)
If end
Algorithm ends
Algorithm: Isfull
Input: Q, Queue

Output: Boolean
Method:
If (R==SIZE)
Return (yes)
Else
Return (no)
If end
Algorithm ends
Algorithm: Front
Input: Q, Queue
Output: element in the front
Method:
If (Isempty (Q))
Print no front element?
Else
Return (Q[F])
If end
Algorithm ends
2. a) Describe the two methods of representing a graph.
Ans :- Two ways of representating Graph
DIRECTED GRAPH :- A graph that has an ordered pair of vertices, (x,y). Here , X is the tail and y is
the head of the edge. There is a path from vertex X to vertex Y. However , a path from y to x may or
may not exist . A path from y to x will be represented by e = (y, x) . Therefore , e = (X , Y) and e = (Y ,
X) are to seprate edges for a directed graph.
DIRECTED GRAPH
The graph contains five vertices,namely,v1,v2,v3,v4, and v5. The graph contains four directed
edges,namely,(v1,v2) , (v2,v3) , (v4,v3) , (v4,v1) , (v4,v5) , and (v5,v1).
UNDIRECTED GRAPH :- A graph that has an unordered pair of vertices representing an edge. This
means that if e = (v ,w) ,then (v, w) and (w ,v) are considered as the same edge.
For EX :UNDIRECTED GRAPH
b) Design an algorithm to generate all prime numbers between 10 and 20.
Ans.:- Algorithm: Primality_Testing (Second approach)
Input : between 10 & 20 , number
flag, test condition
Output : flag updated
Method
flag = 0
for(i=2 to square_root(n) in steps of +1 and flag = 0)

if( n % i = 0) // n mod i
flag = 1
end_if
end-for
if(flag = 0)
display Number is prime?
else
display Number is not prime?
end_if
Algorithm ends
3. a) Trace out the algorithm Max Min on a data set containing atleast 8 elements.
Ans:- Steps to perform MaxMin on a data set (2,4,6,3,8,1,9,7) are:
(2,4,6,3) (8,1,9,7)
((2,4)(6,3)) ((8,1)(9,7))
In sublist (4,6), max is 6 and min is 4. In sublist (8,9), max is 9 and min is 8.
Comparing max and min values of sublist (2,4) and sublist (6,3), value of max is 6 and min is 2.
Therefore, for sublist (2,4,6,3) max is 6 and min is 2.
Similarly, comparing max and min values of sublist (8,1) and sublist (9,7), value of max is 9 and min
is 1.
Therefore, for sublist (8,1,9,7) max is 9 and min is 1.
Finally, comparing max and min values of sublist (2,4,6,3) and sublist (8,1,9,7), value of max is 9 and
min is 1.
b) Design an algorithm to sort the elements using merge sort.
Ans:- Algoritm : MERGESOt
Input : low,high,the lower and upper limits of the list to be sorted
A,the list of elements
Output : A, Sorted list
Method:
If (low < high)
Mid (low +high )/2
MERGESORT(low,mid)
MERGESORT(mid,high)
MERGE(A,low,mid,high)
Ifend
Algorithm ends
4. What are preorder, Inorder, postorder traversals of a binary tree? Design recursion
algorithms to implement them and explain with the help of an example.
Ans:- Traversal is the most important operation done on a binary tree. Traversal is the process of
visiting the verticesof the tree in a systematic order. Systematic means that every time the tree is

traversed it should yield the same result.


PRE-ORDER TRAVERSAL
In this traversal , the nodes are visited in the order of root, Left child and then right child ,i.e.,
1) Visit the root node first.
2) Go to the first left sub-tree.
3) After the completion of the left sub-tree, Go to the right sub-tree.
Here , the lleaf nodes represent the stopping criteria. We go to the sibling sub-tree after the traversal
of a sub tree.
IN-ORDER Traversal
In this traversal , the nodes are visited in the order of the left child,root and then right child.i.e., the
left sub-tree is traversed first, then the root is visited and then the right sub-tree is traversed. Here
also,the left nodes denotes the stopping criteria.
POST-ORDER Traversal
In this traversal, the nodes are visited in the order of left child,right child and then root. i.e.,the left
sub-tree is traversed first, then the sibling is traversed next.the root is visited last.
The recursion algorithm
Algorithm: Pre-order Traversal
Input: bt, address of the root node
Output: Preorder sequence
Method:
if(bt != NULL)
{
Display([bt].data)
Pre-order Traversal([bt].Lchild)
Pre-order Traversal([bt].Rchild)
}
Algorithm ends.
Algorithm: In-order Traversal
Input: bt, address of the root node
Output: Inorder sequence
Method:
if(bt != NULL)
{
In-order Traversal([bt].Lchild)
Display([bt].data)
In-order Traversal([bt].Rchild)
}
Algorithm ends.
Algorithm: Post-order Traversal

Input: bt, address of the root node


Output: Postorder sequence
Method:
if(bt != NULL)
{
Post-order Traversal([bt].Lchild)
Post-order Traversal([bt].Rchild)
Display([bt].data)
}
Algorithm ends.
5. a) What is binary search? Develop a recursive algorithm for binary search.
Ans:- Binary search is necessary to have the vector in an alphabetical or numerically increasing
order .
Consider an example where we have to search for the name Steve in a tlephone directory that is
sorted alphabetically . in this case ,we donot search for the name sequentially .instead, we open the
telephone directory at the middle to open the telephone directory at the middle to determeine which
half contains the name.
Recursive algorithm for binary search
Algorithm : Binary search
Input: A,vector of n elements
K,earch elements
Output : low-index of k
Method :
Low = l, high = n
While(low <= high-1)
{
Mid = (low + high)2
If(k<a[mid]])
High = mid
Else
Low = mid
If end
}
While end
If (k= A[low])
{
Write ( search successful)
Write( k is at location low)
Exit();

}
Else
Write(search unsuccessful);
If end;
Algorithm ends;
b) What are the two methods of representing a binary tree?
Ans:- The two methods of representing binary tree are:? Static allocation and,
? Dynamic allocation
In static allocation ,we have two ways of representing the binary tree.one is through the use of
adjacency matrices and other through the use of single represention dimensional array
representation.
6. a) Design an algorithm to check whether a given string is a palindrome or not.
Ans :- Algorithm: check whether the string is a palindrome or not
Input: string, flag
Output: string is a palindrome
Method:
count = 0
while (the next character ch in the string is not empty)
a(count) = ch
count = count+1
end while
half = count/2palin = true
for (i=1 to half in steps of 1 and j=count to half in steps of 1 do)
if (a (i)! =a (j))
palin = false
break
end if
if (palin = true)
Display String is a palindrome
else
Display String is not a palindrome
end if
end for
Algorithm ends
b) Trace out the algorithm quick sort on the data set {1,5,7,19,15,8,9, 10}.
Ans :{(1),5,7,19,15,8,9, 10}
{(1),5,7,15,19,8,9, 10}

{1,5,7,(15),10,8,9, 19}
{1,5,7,(10),15,8,9, 19}
{1,5,7,(10),8,15,9, 19}
{1,5,7,8,10,15,9, 19}
{1,5,7,8,10,9,15, 19}
{1,5,7,8,9,10,15, 19}
7. a) What is validation and testing of algorithms?
Ans :- Validating:- Once an algorithm has been devised it become necessary to show that it works it
computer the correct to all possible, legal input. One simply way is to code into a program. However
converting the algorithm into program is a time consuming process. Hence,it is essential to be
reasonably sure about the effectiveness of the algorithm beforeit is coded. This process, at the
algorithm level,is calledvalidation. Several mathematical and other empirical method of validation
are available. Providing the validation of an algorithm is a fairly complex process and most often a
complete theoritical validation though desirable, mey not be provided. Alternately, algorithm
segment,which have been proved elsewhere may be used and the overall working algorithm may be
empirically validated for several test cases.And, The process of measuring the effectiveness of an
algorithm before it is coded to know the algorithm is correct for every possible input.This process is
called validation.
Example :- This article describes the algorithms for validating bank routing numbers and credit card
number using
the checksum built into the number. While they differ in how they are generated, the technique used
for both is similar.
Testing : The test of an algorithm is that the program based on the algorithm should run
satisfactorily. Testing a program really involves two phases a) debugging and b) Profiling. Debugging
is the process of executing programs with sample datasets to determine if the results obtained are
satisfactory.When unsatisfactory results are generated ,suitable changes are made in the program to
get the desired results. On the other hand,profiling or performance measurement is the process of
executing a correct program on different data sets to mesure the time and space that it takes to
compute the results.
b) Explain the terms with examples
i) Finite graph
Ans:-A graph with a finite number of vertices as well as finite number of edges is called a finite
graph.
Finite graph
ii) Isolated and pendent vertices
Ans :- A vertex having no incident edge is called an isolated vertex. Vertex v4 and v7 are isolated
vertices(in fig). A vertex of degree one is called a pendent vertex or an end vertex. Vertex v3 is
pendent vertex (in fig).
Graph ontaining isolated vertices and pendent vertex

iii) NULL graph


in the definition of a graph G = ( V , E) it is possible for the edge set E to be empty. Such a graph ,
without any edges, is called a null graph.
iv) Path.
Ans.:- if a walk has the restriction of no repetition of vertices and no edge is retraced it is called a
path.
8. Write short notes on :
a) Debugging
Ans.- Debugging is the process of executing programs with sample datasets to determine if the
results obtained are satisfactory. When unsatisfactory results are generated, suitable changes are
made in the program to get the desired results. On the other hand, profiling or performance
measurement is the process of executing a correct program on different data sets to measure the
time and space that it takes to compute the results.
b) The need for recursion
Ans.:- The need of recursion is :
1) Mathematical functions such as factorial and fibonaci series generation can be easily
implemented using recursion than iteration.
2) in iterative techniques looping of statement is very much necessary..
c) Incidence matrix.
Ans.:- The incidence matrix contains only two elements , o and 1. Such a matrix is called a binary
matrix or a (0,1) matrix. Since every edge is incident on exactly two vertices, each column of a has
exactly two 1.The number of 1? in each now equals the degree of the corresponding vertex. A row
with all 0? , therefore ,represents an isolated vertex. Parallel edges in a graph produce identical
columns in its incidence matrix.