Sunteți pe pagina 1din 20

Q.1. Define an algorithm. What are the properties of an algorithm ?

A.1.Coding is perhaps the last stage in the process of programming. Programming involves
various activities from the stage of conceiving the problem up to the stage of creating a model to
solve the problem. This formal representation of this model as a sequence of instructions is
called an algorithm. The properties of an algorithm are :-
1) Input
2) Output
3) Definiteness
4) Effectiveness
5) Termination
Therefore, an algorithms can be defined as a sequence of definite and effective instructions,
which terminates with the production of correct output from the given input.
Q.2. Write a note on i) devising ii) validating and iii) testing of algorithms.
A.2.i) Devising :-
The process of devising an algorithm is both an art and a science. This is one part that cannot be
automated fully. Let us consider the following example :-
Problem: finding the largest value among n > = 1 numbers.
Input: the value of n and n numbers.
Output: the largest value
Steps:
1. Let the value of the first be the largest value denoted by BIG.
2. Let R denote the number of remaining numbers. R = n -1
3. If R ! = 0 then it is implied that the list is still not exhausted. Therefore look the next
number called NEW/.
4. Now R becomes R-1.
5. If NEW is greater than BIG then replace BIG by the value of NEW.
6. Repeat step 3 to 5 until R becomes zero.
7. Print BIG
8. Stop
ii) Validating
Once an algorithm has been devised, it becomes necessary to show that it works. i.e. it
computes the correct answer to all possible, legal input. One simple way is to code it into a
program. Hence it is essential to be reasonably sure about the effectiveness of the algorithm
before it is coded. This process, at the algorithm level, is called validation. 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 theoretical validation,
through desirable ,may not be provided.
iii) Test of an algorithm
The ultimate test of an algorithm is that the programs based on the algorithm should run
satisfactorily. Testing a program really involves two phases a) debugging 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 correcting a correct program on
different data sets to measure the time and space that it takes to compute the result. However,
it is pointed out that debugging can also indicate the presence of errors but not the absence
of it. Even after it produces satisfactory result with say 10000 data sets, its result may be
faulty with 10001th set. In order to actually prove that a program is perfect, a process is
called proving is taken up.
Q.3 What is a linear data structure ? Give examples. Describe how an array is represented.
A.3 A data structure in which every data element has got exactly two neighbors or two adjacent
elements except two elements having exactly one data element is called a linear data structure.
Array and its representation
Array is a finite ordered list of data elements of same type. In order to create an array it is
required to reserve adequate number of memory locations. The allocated memory should be
contiguous in nature. The size of the array is finite and fixed up as a constant. Some of the
important operations related to arrays are,
Creation () A[n], Array created (reservation of adequate number of memory locations) memory
reserved;
Write (A, i, e)- Updated array with e at i
th
position;
Compare (i, j, Relational operator)- Boolean;
Read (A, i)-e element at ith position;
Search (A, e)-Boolean
Representation of a single Dimensional Array

3 7 -8 10 15 5 50 20



The 1 st element is at (1000 + 0) th location
2 nd element is at (1000 + 2) th location
3 rd element is at (1000 + 4)th location


..
i th element is at (1000 + (i 1)*2)th location
Q.4 Write algorithms to implement the following operations on a stack - create, push, pop.
A.4. Algorithm: Create
Output: S, Stack created
Method:
Declare S[SIZE] // Array of size = SIZE
Declare and Initialize T = 0 //Top pointer to remember the number of elements.
Algorithm ends
Algorithm: Push
Input: (1) S, stack; (2) e, element to be inserted; (3) SIZE, size of the stack; (4) T, the top
pointer
Output:(1) S, updated; (2) T, updated
1 2 3 4 5 6
1000 1002 1004 1006 1008 1010
Method:
If (Isfull(S)) then
Print(stack overflow)
Else
T = T + 1;
S[T] = e
If end
Algorithm ends
Algorithm: Pop
Input: (1) S, stack;
Output: (1) S, updated; (2)T, updated; (3) e element popped
Method:
If (Isempty(S)) then
Print(stack is empty)
Else
e = S[T]
T = T-1;
If end
Algorithm ends
Q.5 What is a first-in-first-out data structure ? Write algorithms to perform the following
operations on it create, insertion, deletion, for testing overflow and empty conditions.
A.5 A queue is an ordered list in which all insertions take place at one end called the rear end,
while all deletions take place at the order end called the from end. Queue is a linear data
structure which works based on the strategy first-in-first out (FIFO).
Create algorithm
Algorithm: Create
Output: S, Stack created
Method:
Declare S[SIZE] // Array of size = SIZE
Declare and Initiative T = 0 // Top pointer to remember the number of elements
Algorithm ends
ii) Algorithm: Insertion
Input: (1) Q, Queue; (2) e, element to be inserted; (3) SIZE, size of the Queue; (4) E, the front
pointer; (5) R, the rear pointer
Output: (1) Q, uploaded, (2)F, updated; (3)R, updated
Method: If (Isfull (Q)) then
Print (overflow)
Else
R = R +1;
Q[R]=e
If(F = = 0)
F = 1;
If end
If end
Algorithm ends
iii) Deletion
Algorithm: Deletion
Input: (1) Q, Queue; (2) SIZE, size of the Queue, (3) F, the front pointer; (4) R, the rear
pointer
Output: (1) Q, uploaded; (2)F, updated; (3) R, updated; (4)e, element if deleted;
Method:
If (Isempty (Q))then
Print(Queue is empty)
Else
e = Q[F]
If(F = =R)
F = R = 0;
Else
F = F + 1;
If end
If end
Algorithm ends

Q.6 What is a graph ? What are the two ways of representing a graph ? Describe with the help
of illustrative examples.
A.6.A graph G = (V, E) consist of a set of objects V = {v
1,
v
2
..} called vertices, and another set
E = {e
1,
e
2
,..} whose elements are called edges. Each edges e
k
in E is identified with an
unordered pair (v
1
,V
1
) of vertices. The vertices v
1,
v
1
associated with edge e
k
are called the end
vertices of e
k
. A graph that has neither self-loop nor parallel edges are called a simple graph,
otherwise it is called general graph. It should also be noted that, in drawing a graph, it is
immaterial whether the lines are drawn straight or curved, long or short. The two ways of
representing a graph are :- Finite and Infinite Graph.
Incidence and Degree
When a vertex v
1
, is an end vertex of some edges e
1,
v
1,
and e
1
are said to be incident with (on or
to) each other. The number of edges incident on a vertex v
1
, with self-loops counted twice is
called the degree, d(v
1
) of vertex v
1
. For example, d(v
1
) = d(v
3
) = d(v
4
) = 4 and d(v
1
) = 1.
Isolated Vertex, Pendent Vertex and Null Graph
A vertex having no incident edges is called an isolated vertex. In other words, isolated vertices
are vertices with zero degree. For example Vertex v
4
and v
7
are isolated vertices. A vertex of
degree one is called a pendent vertex or an end vertex. 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.








Walk, Path and Connected Graph
A walk is a sequence of alternating vertices and edges, starting with a vertex and ending with a
vertex with any number of revisiting vertices and retracing of edges. If a walk has the restriction
of no repetition of vertices and no edge is retraced it is called a path. If there is a walk to every
vertex from any other vertex of the graph then it is called a connected graph.
Q.7 What is a circular queue ? Write algorithms to implement the insertion and deletion
operations.
A.7 A circular queue uses the same conventions as that of linear queue. Using front will always
point one position counterclockwise from the first element in the queue. In order to add an
element, it will be necessary to move rear one position clockwise. Similarly, it will be necessary
to move front one position clockwise each time a deletion is made.
Algorithm: Insertion
Input: (1) CQ, Circular Queue; (2) e, element to be inserted; (3) SIZE, size of the Circular
Queue; (4) F, the front pointer; (5) R, the rear pointer
Output: (1) CQ, updated; (2) F, updated; (3) R, updated
Method :
If(Isfull(CQ)) then
Print ( overflow)
Else
R = R mod SIZE + 1;
CO [R] = e
If( Isempty (CQ))
F = 1;
If end
If end
Algorithm ends
Algorithm: Deletion
Input: (1) CQ, Circular Queue; (2) SIZE, size of the CQ; (3) F, the front pointer; (4) R, the rear
pointer
Output: (1) CQ, updated; (2) F, updated; (3) R, updated; (4) e, element if deleted;
Method:
If (Isempty (CQ)) then
Print ( Queue is empty)
Else
e = CQ[F]
If (F = = R)
F = R = 0;
Else
F = F mod SIZE + 1;
If end
If end
Algorithm ends

Q.8 Write an algorithm to find the roots of a quadratic equation.
A.8 Algorithm: Quadratic_solver
Input: a, b, c the co-efficients of the Quadratic Equation
Output: The two roots of the Equation
Method:
disc = ((b * b)-(4*a*c))
if (disc = 0)
display roots are real and equal
r1 = -b/2a
r2 = -b/2a
display r1
display r2
else
if (disc > 0)
display roots are real and distinct
r1 = (-b + sqrt (disc))/2a
r2 = (-b + sqrt(disc))/2a
else
display roots are complex
display real part,-b/2a
display imaginary part, sqrt(absolute_value_of(disc))
display the two root exists in conjugates
end_if
Algorithm ends





Q.9 Design an algorithm to check whether a given string is a palindrome or not.
A.9. Algorithm: PalindromeString(Str, R)
Input: Str is an character array containing alpha-numeric character set.
Output: R will be 0 if Str is not Palindrome Else R will be 1.
Step 1: StrLen = StringLength (Str) [Calcucate the length of the Str ]
Step 2: i = 0, j = (StrLen -1)
Step 3: R = 1
Step 4: While (i < j)
If (Str[i] ! = Str[j])
R = 0
Return.
EndIf
i= i + 1
J = j + 1
Endwhile
Step 5: Return

Q.10 Develop an algorithm to generate all the prime numbers between the given 2 limits.
A.10. Algorithm: Prime number
Input: n, number flag
Output: flag updated
Method:
flag = 0
for (i = 2 to n/2 in steps of +1 and flag = 0)
if (n % i = 0) n mod i
flag = 1
end-if
if (flag = 0)
display Number is prime
Algorithm ends

PART - A
I. Say whether the following statements are true or false.
1) Definiteness is one of the properties of an algorithm.
A.1) True
2) Graph is a linear data structure.
A.2) False
3) A tree is a connected graph.
A.3) True
4) The data structure used by recursion is stack.
A.4) False
5) Queue works on the strategy First in First out.
A.5) True
II. Using suitable word or phrase fill up the blanks in the following sentences:
1) Algorithm is the process of executing a correct program on data sets and
measuring the time and space.
2) Tree is a Non-linear data structure.
3) For a graph with n number of nodes the number of edges to form a tree is
a vertices .
4) Last in First out Data structure is referred to as Stack.
5) A binary tree of depth K has maximum of two number of
nodes.
6) A simple graph is a graph without self loop and parallel edges.
7) The two methods of searching are sequential search and binary search .

III. Write brief answers to the following questions:
Q.1) Define algorithm. What are its properties?
A.1) An algorithms can be defined as a sequence of definite and effective instructions, which
terminates with the production of correct output from the given input. Programming involves
various activities from the stage of conceiving the problem up to the stage of creating a model to
solve the problem. The properties of an algorithm are :-
1) Input
2) Output
3) Definiteness
4) Effectiveness
5) Termination

Q.2) Give atleast four real life examples where we use stack operations.
A.2) The four examples where we use stack operations are :-
1) Pile of Books
2) Pile of Plates
3) bangles in hand
4) Pile of Cds.

Q. 3) Differentiate full and complete binary trees.
A.3)A complete binary tree is one which allows sequencing of the nodes and all the previous
levels are maximally accommodated before the next level is accommodated i.e. the siblings are
first accommodated before the children of any one of them. And full binary tree which is
maximally accommodated with all leaves at the same level is called full binary tree. A full binary
tree is always complete but complete binary tree need not be full.


Q. 4) What are the demerits of recursion?
A.4) the demerits of recursion are :-
1) Many programming languages do not support recursion; hence recursive mathematical
function is implemented using iterative methods.
2) Even though mathematical functions can be easily implemented using recursion it is always at
the cost of execution time and memory space.
3) A recursive procedure can be called from within or outside itself and to ensure its proper
functioning it has to save in some order the return address so that ,a return to the proper location
will result when the return to a calling statement is made.
4) The recursive programs needs considerably more storage and will take more time.

PART - B
Q.1. a) What are the characteristics of an algorithm? Describe with an example.
b) Write an algorithm to implement any three operations of a queue.

A.1.a) The characteristics of an algorithm are :-
1) Input
2) Output
3) Definiteness
4) Effectiveness
5) Termination
Let us take a scenario of a man brushing his own teeth (natural denture) as an algorithm are
Step 1. Take the brush
Step 2. Apply the paste
Step 3. Start brushing

Step 4.Rinse

Step 5. Wash

Step 6. Stop

b) 1)Algorithm: Isempty
Input: Q, Queue
Output: Boolean
Method:
If (F = = 0)
Return(yes)
Else
Return(no)
If end
Algorithm ends
2) Algorithm: Isfull
Input: Q, Queue
Output: Boolean
Method:
If (R = = SIZE)
Return (yes)
Else
Return (No)
If end
Algorithm ends
3) Algorithm: Insertion
Input: (1) Q, Queue; (2) e, element to be inserted; (3) SIZE, size of the Queue; (4) E, the front
pointer; (5) R, the rear pointer
Output: (1) Q, uploaded, (2)F, updated; (3)R, updated
Method: If (Isfull (Q)) then
Print (overflow)
Else
R = R +1;
Q[R]=e
If(F = = 0)
F = 1;
If end
If end
Algorithm ends
Q. 2. a) Describe the two methods of representing a graph.
b) Design an algorithm to generate all prime numbers between 10 and 20.
A.2.a) The two ways of representing a graph are :- Finite and Infinite Graph. Although in the
definition of a graph neither the vertex set V nor the edge set E need be finite, in most of the
theory and almost all applications there sets are finite. A graph with a finite number of vertices as
well as a finite number of edges is called a finite graph.
b) Algorithm: Primality_testing
Input : between 10 & 20, number flag test condition
Output: flag updated
Method:
flag = 0
for (I = 2 to square _root (n) in step 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
Q. 3. a) Trace out the algorithm Max Min on a data set containing atleast 8 elements.
b) Design an algorithm to sort the elements using merge sort.
A.3.a) The algorithm Max Min on a data set containing atleast 8 element are :-
Algorithm: Max-Min
Input: p,q, the lower and upper limits of the dataset max, min, two variables to return the
maximum and minimum values in the list
Output: the maximum and minimum values in the data set
Method:
If (p = q) then
max = a(p)
min = a(q)
Else
If ( p q 1) then
If a(p) > a(q) then
max = a(p)
min = a(q)
Else
max = a(q)
min = a(p)
If End
Else
m = (p + q) / 2
max-min (p,m,max1,min1)
max-min (m + 1,q, max2, min2)
max- large (max1, max2)
min- small(max1,max2)
If End
If End
Algorithm Ends
b) An algorithm to sort the elements using merge sort are:-
Algorithm: MERGE SORT
Input: low, high, the lower and upper limits of the list to be sorted A, 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)
If end
Algorithm ends





Q. 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.
A.4. 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 leaf nodes represent the stopping criteria. We go to the sibling sub-tree after the
transversal of a sub-tree.
In-Order Traversal
In this transversal, the nodes are visited in the order of left child, root and the right child i.e. the
left sub-tree is transversal first , then the root is visited and then the right sub-tree is tranversed.
Here also, the leaf nodes denote 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.

Recursion is an offshoot of the concept of subprograms. A subprogram as we know is the
concept of writing separate modules, which can be called from other points in the program or
other programs. Then came a concept wherein any subprogram.can call any other subprogram.
The control goes to the called subprogram, performs the assigned tasks and comes back to the
caller programs. The general procedure for any recursive algorithm is as follows.
1. Save the parameters, local variables and return addresses.
2. If the termination criterion is reached perform final computation and go to step 3,
otherwise perform final computations and go to step 1.
3. Restore the most recently saved parameters, local variables and return address and go to
the latest return address.
Example:-
Algorithm: Fibonacci
Input: n, the position at which the Fibonacci number has to be computed
Output: nth Fibonacci number
Method:
If (n = = 0)
Return (0)
Else
If ( n = = 1)
Return (1)
Else
Return (Fibonacci (n -1) + Fibonacci (n -2))
If end
If end
Algorithm ends

Q.5. a) What is binary search? Develop a recursive algorithm for binary search.
b) What are the two methods of representing a binary tree?
A.5.a) Binary search method is also relatively simple method. For this method it is necessary to
have the vector in an alphabetical or numerically increasing order. A search for a particular item
with X resembles the search for a word in the dictionary. The approximate mid entry is located
and its key value is located and its key value is examined. If the mid value is greater than X, then
the list is chopped off at the (mid -1)th location. Now the list gets reduced to half the original list.
The middle entry of the left-reduced list is examined in a similar manner. This procedure is
repeated until the item is found or the list has no more elements.
Algorithm: binary search
Input: A, vector of n elements
K, search element
Output: low-index of k
Method: low = 1, 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) The two ways of representing a binary tree are :-
Static allocation and Dynamic allocation

Q. 6. a) Design an algorithm to check whether a given string is a palindrome or not.
b) Trace out the algorithm quick sort on the data set {1,5,7,19,15,8,9, 10}.
A.6.a) Algorithm: PalindromeString(Str, R)
Input: Str is an character array containing alpha-numeric character set.
Output: R will be 0 if Str is not Palindrome Else R will be 1.
Step 1: StrLen = StringLength (Str) [Calcucate the length of the Str ]
Step 2: i = 0, j = (StrLen -1)
Step 3: R = 1
Step 4: While (i < j)
If (Str[i] ! = Str[j])
R = 0
Return.
EndIf
i= i + 1
J = j + 1
Endwhile
Step 5: Return
b) Algorithm: QuickSort
Input: p, q, the lower and upper limits of the list of elements A to be sorted
Output: A, the sorted list
Method:
If (p < q)
j = q + 1;
PARTITION (p ,j)
QuickSort (P, j 1)
QuickSort (j + 1, q)
If end
Algorithms ends





Q. 7. a) What is validation and testing of algorithms?
b) Explain the terms with examples
i) Finite graph
ii) Isolated and pendent vertices
iii) NULL graph
iv) Path.
A.7.a) Once an algorithm has been devised, it becomes necessary to show that it works, i.e it
computes the correct answer to all possible , legal inputs. Once simple way is to cock it into a
program . However, converting the algorithms into programs is a time consuming process.
Hence, it is essential to be essential to be reasonably sure about the effectiveness of the algorithm
before it is coded. This process, at the algorithm level, is called validation. The ultimate test of
an algorithm is that the programs based on the algorithm should run satisfactorily. Testing a
program really involves two phases a) debugging , b) profiling. Debugging is the process of
executing program 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.
b) i) Although in the definition of a graph neither the vertex set V nor the edge set E need be
finite, in most of the theory and almost all applications there sets are finite. A graph with a finite
number of vertices as well as a finite number of edges is called a finite graph.
ii) A vertex having no incident edge is called an isolated vertex. In other words, isolated vertices
are vertices with zero degree. A vertex of degree one is called a pendent vertex or an end vertex.
Two adjacent edges are said to be in series if the common vertex is of degree two.
iii) In a definition of a graph G = (V, E), it is possible for the edge set E to be empty. Such a
graph without edges is called a null graph.
iv) A walk is a sequence of alternating vertices and edges,, starting with vertex and ending with a
vertex with any number of revisiting vertices and retracing of edges. If a walk has the restriction
of no repetition of vertices and no edge is retraced it is called a path.

Q. 8. Write short notes on :
a) Debugging
b) The need for recursion
c) Incidence matrix.

A.8.a) Debugging:- Debugging is the process of executing program with sample datasets to
determine if the result obtained are satisfactory. When unsatisfactory result are generated,
suitable changes are made in the program to get the desired result.

b) Incidence Matrix:- Let G be a graph with n vertices , e edges and no self-loops. Define an n by
e matrix A =[a
ij
], whose n rows correspond to the n vertices and the e columns correspond to the
e edges as follows :
The matrix element
A
ij
= 1, if j
th
edges e
j
is incident on i
th
vertex v
i
and = 0 , otherwise.

a b c d e f g h
v1 0 0 0 1 0 1 0 0
v2 0 0 0 0 1 1 1 1
v3 0 0 0 0 0 0 0 1
v4 1 1 1 0 1 0 0 0
v5 0 0 1 1 0 0 1 0
v6 1 1 0 0 0 0 0 0

Such a matrix A is called the vertex-edges incidence matrix ,or simply incidence matrix. Matrix
A for a graph G is sometimes also written as A(G). A graph and its incidence matrix are given in
matrix. The following observation about the incidence matrix A, can readily be made.
1. Since ever edges is incident on exactly two vertices, each column of A has exactly two.
2. The number of 1 in each row equals the degree of the corresponding vertex.
3. A row with all 0 therefore represents an isolated vertex.

c) The need of Recursion When iteration can be easily used and also supported by most
programming languages. The answer is that iteration has certain demerits as is made clear
below:-
1. mathematical functions such as factorial and Fibonacci series generation can be easily
implemented using recursion than iteration.
2. In iterative technique looping of statement is very much necessary.

S-ar putea să vă placă și