Sei sulla pagina 1di 6

Define algorithm? What are its properties?

What
are the advantages of an algorithm?
An algorithm is a set of instructions that provide
step-by-step specifications to perform a task.
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.
Advantages of an algorithm:
1. Algorithm identifies step by step procedure, the
major decision points and variables necessary
to solve the problem.
2. Algorithm helps in developing a program.
3. An algorithm breaks the complex problem into
smaller manageable parts which helps in
solving a problem.

What is debugging and profiling?
Debugging is the process of identifying and fixing
the errors in a program. Errors in a program can be
identified by executing the program with a sample
dataset. If the result produced is not correct then
changes to the code are made for producing the
correct results.
Profiling is the process of measuring the
performance of the program by executing it on
different data sets. Performance of a program is
measured by recording the time and memory space
that the program takes during its execution.

What is Pseudo code? Give an example.
Pseudo code is an informal high-level description
of the operating principle of a computer program or
other algorithm. It is also an artificial and informal
language that helps programmers develop
algorithms. Pseudo code is a "text-based" detail
(algorithmic) design tool. For example,
If a student's grade is greater than or equal to 60
Print "passed"
else
Print "failed"

How did you validate the algorithms?
Once an algorithm has been devised it becomes
necessary to show that it works, that is, it computes
the correct answers to all possible, legal input. One
simply way is to code into a program. However,
converting the algorithm into programs is a time
consuming process. 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 methods of
validation are available. Providing the validation of
an algorithm is a fairly complex process and most
often a complete theoretical validation though
desirable, may 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. Such method, although suffice in most
cases, may often lead to the presence of
unidentified bugs or side effect later on. 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 numbers using the checksum built
into the number. While they differ in how they are
generated, the technique used for both is similar.

What is problem solving? Illustrate the different
aspects in it.
The process of working through details of a
problem to reach a solution is known as problem
solving. It may include mathematical or systematic
operations and can be a gauge of an individual's
critical thinking skills.
The different aspects of problem solving are as
follow: -
When you visit a doctor you will find that s/he asks
many questions to solve the problem that you have.
The same is true when you visit a Motor
Dealership to have your car repaired - you may be
asked about the symptoms leading up to the car
problems. The Doctor and the Mechanic are
Problem Solving when they ask you lots of
questions. You expect that they have great Trouble
Shooting Ability and can fix whatever is wrong.

What are the general steps in solving a problem?
1. Become aware of the problem
2. Define the problem
3. Choose the particular part of the problem to be
solved
4. Identify potential solutions
5. Evaluate the valid potential solutions to select
the best one
6. Develop an action plan to implement the best
solution.

Profiling is the process of executing a correct
program on data sets and measuring the time and
space it takes to compute the results.
Give at least 5 real life examples where queue is
used.
Real life examples of queue are:
1. A queue of people at ticket-window: The
person who comes first gets the ticket first. The
person who is coming last is getting the tickets
in last. Therefore, it follows first-in-first-out
(FIFO) strategy of queue.
2. Vehicles on toll-tax bridge: The vehicle that
comes first to the toll tax booth leaves the
booth first. The vehicle that comes last leaves
last. Therefore, it follows first-in-first-out
(FIFO) strategy of queue.
3. Phone answering system: The person who
calls first gets a response first from the phone
answering system. The person who calls last
gets the response last. Therefore, it follows
first-in-first-out (FIFO) strategy of queue.
4. Luggage checking machine: Luggage
checking machine checks the luggage first that
comes first. Therefore, it follows FIFO
principle of queue.
5. Patients waiting outside the doctor's clinic:
The patient who comes first visits the doctor
first, and the patient who comes last visits the
doctor last. Therefore, it follows the first-in-
first-out (FIFO) strategy of queue.

Define stack? How do you represent a stack? Give
at least 5 real life examples where we use stack
operations.
A stack is a linear data structure of ordered list in
which elements are inserted and deleted from same
end which is known as top. It works on the strategy
of first in first out (FIFO).
A stack as in a software "pushdown stack" can be
represented as an array with a count of how many
elements are used.
The real life examples of stacks are:
1. 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.
2. 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.
3. Sacks full of wheat placed one over other:
The sack at the top is removed first and the
sack at the bottom is removed last.
4. 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.
5. Battery cells in a torch: The battery cells in a
torch also follow the same LIFO strategy of
stack.

Name 10 situations that can be represented by
means of graphs. Explain what each vertex and
edge represents.
The situations that can be represented by means of
graphs are:
Example Vertex represents Edgerepresents
1. Displacement Position or state Distance
between the two vertices connected through the
edge
2. Shortest Path City Distance between the
two vertices connected through the edge
3. City Map Places of the city Distance
between the two vertices connected through the
edge
4. Air route Different airports Distance
between the two vertices connected through the
edge
5. Population Growth per year Population for a
year Variation in the population between the
two vertices connected through the edge
6. In mathematical expressions Value
Conditions and calculations
7. Daily temperature report Temperature for a
specific time Variation in the temperature
between the vertices connected through the
edge
8. Child-parent relationship Name of the
person Relationship
9. Organization chart Designation Order or
flow
10. Chemical structure Chemical elements
Bonding between the elements

Sketch all binary trees with six pendent edges.
The following figures show binary trees with six
pendent edges:

Binary Tree with Six Pendent Edges

The preceding figures, A, B, and C, show three
examples of binary trees having six pendent edges.
All the binary trees having six leaf nodes come
under this category.

One of the properties of an algorithm is beauty.
False
What is linked list? Explain singly linked list with
a pictorial representation.
A linked list is a set of elements, usually structures,
where each element contains a pointer or index to
the "next" element, along with the data represented
by the element. Often, the elements are allocated
from the heap and in this case, pointers are used.
Sometimes, a fixed number of elements are
contained in an array and in this case, indices are
used. In an array implementation, read pointer is an
index.
Types of linked lists are: -
Singly linked list: - A singly linked list is a simple
data structure that acts as a base for various other
data structures. It provides a convenient way to
organize and represent data for efficient
manipulation in computer application. In a singly
linked list, a list contains nodes which have a data
field as well as a next field, which points to the
next node in line. The last element's pointer is null.
This type of list can be traversed in only one
direction.

A singly linked list whose nodes contain two fields:
an integer value and a link to the next node
Doubly linked list: - In a doubly linked list, each
node contains, besides the next-node link, a second
link field pointing to the previous node in the
sequence. The two links may be called forward(s)
and backward(s), or next and previous. This type of
list can be traversed in two directions, making
insertion and deletion a bit easier, at the cost of
extra memory.

A doubly linked list whose nodes contain three
fields: an integer value, the link forward to the next
node, and the link backward to the previous node
Circularly linked list: - The same as Singly or
Doubly linked, except that the last element's
pointer points back to the first element's pointer.
These types of lists are often used as queues.

A circular linked list
Multiply linked list: - In a multiply linked list,
each node contains two or more link fields, each
field being used to connect the same set of data
records in a different order (e.g., by name, by
department, by date of birth, etc.). While doubly
linked lists can be seen as special cases of multiply
linked list, the fact that the two orders are opposite
to each other leads to simpler and more efficient
algorithms, so they are usually treated as a separate
case.

List the general operations on a linked list.
The general operations on a linked list are as
follow:
1. Creation of a linked list,
2. Displaying the content of a linked list,
3. Inserting an element at the front or at the rear
end of a linked list,
4. Inserting an element at the specified position of
a linked list,
5. Inserting an element in to a sorted linked list,
6. Deleting an element from a linked list at the
front or at the rear end,
7. Deleting an element from a linked list at the
specified position,
8. Deleting an element e from a linked list if
present,
9. Searching for an element e in the linked list,
10. Reversing a linked list
11. Concatenation of two linked list,
12. Merging of two ordered linked lists,
13. Splitting a linked list

Define queue. How do you represent queue.
Mention its application in computer science
A queue is a linear data structure of ordered list in
which element are inserted at one end known as
Rear and elements are deleted at other end known
as Front end. Queue works on the strategy of first
in first out.
Applications of queue in computer science are: -
1) Printer spooling 2) CPU scheduling
3) Keyboard buffering 4) Mail service.

Give detailed algorithm to compute address of a
data element using row major address computation.
The algorithm to compute address of a data
element using row major address computation is as
follow: -
Algorithm: Address Computation (Row Major)
Input: (1) n, dimension
(2) l1, l3, l2,ln n lower limits
(3) u1, u3, u2,un n upper limits
(4) w, word size
(5) i1, i3, i2,in value of subscripts
(6) B, the base address
Output: A address of the element at (i1, i3,
i2,in)
Method: { (

}

Where



End of algorithm

Define circular queue? What are its advantages?
A circular queue is the implementation of an array
in the form of a ring. In a circular queue if the last
index is occupied by an element then we start
inserting the element from the beginning provided
there is free space. Its advantage is that it makes
more utilization of memory than the linear queue.
Explain queue operation.
1. Create ( ) Q;
2. Insertion (Q, e) updated Q;
3. Deletion (Q) Q, e;
4. Isfull (Q) Boolean;
5. Isempty (Q) Boolean;
6. Front (Q) e;
7. Back (Q);
8. Destroy (Q);

Algorithm: Create
Output: Q, Queue created
Method:
Declare Q [Size]
Declare and initialize R=0
Declare F and initialize F=0
Algorithm ends

Algorithm: Insertion
Input: Q, Queue
e, element to be inserted
F, the front pointer
R, the rear pointer
SIZE, size of the Queue
Output: F updated, R updated and Q 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

Algorithm: Deletion
Input: Q, Queue
e, element to be deleted
F, the front pointer
R, the rear pointer
SIZE, size of the Queue
Output: F updated, R updated, Q updated and e,
element if deleted
Method:
If(Isfull (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

Algorithm: Isfull
Input: Q, Queue
Output: Boolean
Method:
If(R==Size)
Return (yes)
Else
Return (no)
If end
Algorithm ends

Algorithm: Isempty
Input: Q, Queue
Output: Boolean
Method:
If(F==0)
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

Algorithm: Rear
Input: Q, Queue
Output: element in the rear
Method:
If(Isempty (Q))
Print no back element
Else Return (Q[R])
If end
Algorithm ends

What are the serious shortcomings of the binary
search method and sequential search method?
A serious shortcoming of the sequential search
method is that even if the element that you are
trying to search is not present in the given file, the
entire file is searched at least once.
A serious shortcoming of the binary search method
is that it can be applied only to a list in which the
elements are arranged in ascending order.

Data structure used by recursive algorithm is stack

Input is one of the properties of an algorithm.

Algorithm + coding = Programme.
Implements all stack operations.
Algorithms for different operation performed on
stack are as follows:
1. Create ( ) S;
2. Insertion (S, e) updated S;
3. Deletion (S) S, e;
4. Isfull (S) Boolean;
5. Isempty (S) Boolean;
6. Top (S) e;
7. Destroy (Q);

Algorithm: Create
Output: S, Stack created
Method:
Declare S[Size]
Declare T and initialize T=0
Algorithm ends

Algorithm: Push
Input: S, stack;
e, element to be inserted;
T, top pointer;
Size, size of the stack
Output: top updated.
Method:
If(Isfull(S)) then
Print (Overflow)
else
T=T+1;
S[T]=e
If end
Algorithm ends

Algorithm: Pop
Input: S, stack
Output: S, updated deleted;
T, updated;
e, element popped;
Method:
If(Isempty(S)) then
Print (empty)
Else
e=S[T]
T=T-1;
If end
Algorithm ends

Algorithm: Isfull
Input: S, stack
Output: Boolean
Method:
If(T==Size)
Return (yes)
Else
Return (no)
If end
Algorithm ends

Algorithm: Isempty
Input: S, stack
Output: Boolean
Method:
If(T==0)
Return (yes)
Else
Return (no)
If end
Algorithm ends

Design and develop algorithms for multiplying n
integers.
Algorithm: Multiply_n_Integers
Input: integers, number of integers to be
multiplied (n), loop variable (i)
Output: mul, updated
Method:
Display 'Enter the number of elements'
Accept n
Display 'Enter elements one by one'
for (i = 1 to n in steps of 1 do)
Accept a (i)
end_for
mul = 1
for (i = 1 to n in steps of 1 do)
mul = mul*a(i)
end_for
Display 'multiplication of n integers is = ', mul
Algorithm ends

Design an algorithm to generate all prime numbers
within the limits 11 and 12.
Algorithm: to generate all prime numbers between
the limits 11 and 12.
Input: l1 and l2
Output: Prime numbers between 11 and 12
Method:
for (n=11 to 12 in steps of 1 do)
prime=true
for (i=2 to n/2 in steps of 1 do)
if (n % i =0)
prime = false
break
end_if
end_for
if (prime = true)
Display 'Prime number is =', n
end_for
Algorithm ends

Name the important problem types.
Some of the important problem types are as follows
1) Geometric problems 2) Sorting
3) String processing 4) Searching
5) Numerical problems 6) Graph problems
7) Combinatorial problems
Design and develop an algorithm for finding the
middle element in three numbers.
To find the middle element one has to first sort the
numbers in ascending order. The smallest number
becomes the first element in the sorted list and the
largest number becomes the last element in the
sorted list.
Consider three numbers 3, 1, and 7.
The smallest number amongst these three is 1;
therefore, 1 becomes the first element in the sorted
list. Amongst 3 and 7, 3 is the second element. The
larger number 7 is left out and becomes the last
element. Hence the middle number 3 is displayed.
Algorithm : Middle_3_Elements
Input: a, b, c the three numbers to be sorted, two
temporary variables k1, and K2
Output: Middle element in the three numbers.
Method:
If (a<b)
If (a<c)
If (b<c)
m = b
else m = c
end if
else m = a
end if
else
if (b<c)
if (a<c)
m = a
else
m = c
end if
else
m = b
end if
end if
Algorithm ends

Design an algorithm to check whether a given
string is a palindrome or not.
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

A number is said to be a palindrome if the reverse
of a number is same as the original. Design an
algorithm to check whether a number is a
palindrome or not.
Algorithm: check whether the number is a
palindrome or not
Input: number, flag
Output: number is a palindrome
Method:
count = 0
while (number > 0)
n = number%10
a(count)=n
count = count+1
end while
half = count/2
palin = true
for (j=1 to half in steps of 1 and k=count to half in
steps of 1 do)
if (a (j)! =a(k))
palin = false
break
end if
if (palin = true)
Display 'Number is a palindrome'
else Display 'Number is not a palindrome'
end if
end for
Algorithm ends

Design an algorithm to find the reverse of a
number.
Algorithm: Reverse of a number
Input: number
Output: Reverse of a number
Method:
new_number = 0
while (number > 0)
n = number % 10 //n denotes a digit extracted from
the number
number = number / 10
new_number = new_number +n
new_number= new_number*10
end while
new_number = new_number/10
Display 'Reverse number is =', new_number
Algorithm ends

Draw all trees of n labeled vertices for n=1,2,3,4
and 5.
The following figures show the trees for various
values of n, where n represents the number of
vertices in a tree.
For n=1

For n=2

For n =3
There can be a number of trees with 3 labeled
vertices. Some of the examples of the trees with 3
labeled vertices are:


For n=4
Again, there can be a number of trees with 4
labeled vertices. Some of the examples of the trees
with 4 labeled vertices are:


For n=5
Again, there can be a number of trees with 5
labeled vertices. Some of the examples of the trees
with 5 labeled vertices are:



Write adjacency and incidence matrix for a
connected graph that becomes disconnected when
any edge is removed from it.
The following tables show adjacency and incidence
matrices for a connected graph that becomes
disconnected when any edge is removed from it.

Consider a data set of nine elements {10, 30, 45,
54, 56, 78, 213, 415, 500} and trace the linear
search algorithm to find whether the keys 30, 150,
700 are present in the data set or not.
In linear search algorithm, each element in the list
is compared with the given key element. If any of
the elements in the list is equal to the given key
element, the linear search algorithm returns TRUE,
else it returns FALSE.
Let us apply linear search to find the key element
30 in the given list.
Take the first element 10 from the list and compare
it with the key element 30. Clearly the two
elements are not equal.
Take the next element 30 from the list and compare
it with the key element 30. Clearly, the two
elements are equal. The algorithm returns the
TRUE value, and the algorithm is terminated.
Similarly, search for the key elements 150 and 700.
At the end of the search, you will find that the key
elements 150 and 700 are not found in the list.

If the discriminant is negative then the roots will be
of imaginary in nature.
How to device an algorithm? Explain?
The process of devising an algorithm is both an art
and a science. This is one part that cannot be
automated fully. To give a problem description,
one have to think of converting this into a series of
steps, which, when executed in a given sequence
solve the problem. To do this, one has to be
familiar with the problem domain and also the
computer domains. This aspect may never be
taught fully and most often, given a problem
description, how a person proceeds to convert it
into an algorithm becomes a matter of his "style"-
no firm rules become applicable here.
For 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 the BIG then replace
BIG by the value of NEW
6. Repeat Steps 3 to 5 until R becomes zero.
7. Print BIG
8. Stop
End of algorithm

Develop an algorithm to find the number of
Permutations and Combinations for a given n and r.
Permutation of a given number is given by n*(n-
1)*(n-2)...up to r factors.
This is a generalized algorithm for n>2
Algorithm: Permutation of a number for a given r
Input: n and r
Output: Permutation of n
Method:
a) per = 1
for (j = n to n - r + 1 in steps of -1 do) //where j is
a loop variable
per = per*j
end_for
Display ' Permutation = ', per
b) Combination of a number n for a given r is
calculated by
nCr = nPr / r!
Calculate the permutation nPr using the above
algorithm
Calculate the factorial for r using the algorithm
fact = 1
for (j =1 to r in steps of 1 do) //where j is a loop
variable
fact = fact*j
end_for
comb = per / fact
Display ' Combination =', comb
Algorithm ends

Trace the binary search algorithm on a data set of
nine elements {10, 30, 45, 54, 56, 78, 213, 415,
500}
Binary search algorithm can be applied only to the
sorted list of elements. Lets first apply the binary
search algorithm to find the key element 30 in the
following list taken from problem 2:

Take the middle element from the list and compare
it with the key element. Clearly, the middle
element 56 > key element 30. As the key element
is smaller than the middle element, the key element
can only be present in the left sub list that is as
follows:

Again, take the middle element from this list and
compare it with the key element. Clearly, the
middle element 45 > key element 30. As the key
element is smaller than the middle element, the key
element can only be present in the left sub list that
is as follows:

Again, take the middle element from this list and
compare it with the key element. Clearly middle
element 30= key element 30, therefore, the binary
search algorithm returns a TRUE value and the
algorithm is terminated.
Similarly, search for the key elements 150 and 700.
At the end of the search, you will find that the key
elements 150 and 700 are not found in the list.

When is it appropriate to use recursion?
Recursion is used for repetitive computations in
which each action is stated in terms of previous
results. There are two conditions that must be
satisfied by any recursive procedure: -
1. Each time a function calls itself it should get
nearer to the solution
2. There must be a decision criterion for stopping
the process.

Searching for a word in the dictionary is an
example of binary search.

Tree is a non-linear data structure.

Array is linear data structure.

Linked list is a binary data structure.
What are the applications of recursion?
Recursion can be used for repetitive computation in
which each action is stated in terms of previous
result. There are two conditions thats must be
satisfied by any recursive procedure.
1. Each time a function calls itself it should get
nearer to the solution.
2. In iterative techniques looping of statement is
very much necessary.
For example: - Chess playing programs, Alpha-
beta Pruning, Recursive Descent Compilation

Try to know more sorting techniques and make a
comparative study of them.
There are various sorting techniques, such as
bubble sort, quick sort, and shell sort. Each of these
sorting techniques is defined as follows:
Bubble sort: In the bubble sort technique two
elements are compared at a time and if the two
elements are not in ascending order these elements
are interchanged. This process is repeatedly
performed throughout the given list until the list is
completely sorted. To sort a list of n elements using
bubble sort you need to make a total of (n-1)
2

comparisons.
Quick sort: The basic idea underlying quick sort is
to allow a specific element 'a' within the list 'x' to
find its proper position 'j'. The proper position 'j' is
found such that it satisfies the following two
conditions:
The elements on the left hand side of position 'j' are
all smaller than or equal to 'a'
The elements on the right hand side of position 'j'
are all greater than or equal to 'a'
If 'a' satisfies these two conditions, then 'a' is the jth
smallest element in the list and 'a' is placed at jth
position in the finally sorted list. This process is
then repeated for sub arrays x [0..j-1] and x [j+1..n-
1].
Shell sort: In shell sort, the given list x is divided
into sub lists containing every kth element of the
given list. For example, if k=5 then one sub list
contains x [0], x [5], x [10]..., another sub list
contains x [1], x [6], x [11]..., and so on. The
elements of these sub lists are then compared two
at a time and if the two elements are not in
ascending order, these elements are interchanged.
Now, a new value of k is chosen which is smaller
than the previous value of k and the process is
repeated again. This process is repeated until the
value of k is set to 1 so that the sub list consisting
of the entire list is sorted.

Bring out the pros and cons of the algorithms for
exchanging the values of two variables using
computation based and temporary based variable.
Hand simulates both on a pair of values of your
interest.
The problem of interchanging the values associated
with two variables involves a very fundamental
mechanism that occurs in many sorting and data
manipulation algorithms.
Algorithm 1: Computation based.
Algorithm: Exchange_2_Variables
Input: a, b, the two variables whose values to be
exchanged
Output: Exchanged values of a and b
Method: a = a + b // Sum the value of a and b
and assign sum value to a
a = a - b // Subtract b from a and assign
subtracted result to b
b = a - b // Subtract b from a and assign
subtracted result to a
Algorithm ends
Algorithm 2: Temporary variable based.
Algorithm: Exchange_2_Variables
Input: a, b, the two variables whose values to be
exchanged
Output: Exchanged values of a and b
Method: t = a + b // Save the original value of a
in t
a = b // Assign to a original value of b
b = t // Assign to b the original value of a that is
stored in t
Algorithm ends

Hand simulate Insertion Sort on the data set {13,
45, 12, 9, 1, 10, 40}
Let us apply Insertion Sort algorithm on the given
list:


Walk is a sequence of alternating vertices and
edges.

A tree with n vertices has n-1 edges.

One of the properties of an algorithm is structured
False

Circular queue works on the strategy first in first
out. True
Hand simulate straight selection sort on the dataset
{89, 45, 68, 90, 29, 34, 17}
89 45 68 90 29 34 17
i = 7
17 45 68 90 29 34 89
i = 6
17 29 68 90 45 34 89
i = 5
17 29 34 90 45 68 89
i = 4
17 29 34 45 90 68 89
i = 3
17 29 34 45 68 90 89
i = 2
17 29 34 45 68 89 90


Explain insertion sort with an example
Insertion sort is a simple sorting algorithm that
builds the final sorted array (or list) one item at a
time. It is much less efficient on large lists than
more advanced algorithms such as quicksort,
heapsort, or merge sort. However, insertion sort
provides several advantages:
Simple implementation
a) Efficient for (quite) small data sets
b) Adaptive (i.e., efficient) for data sets that are
already substantially sorted: the time
complexity is O(n + d), where d is the number
of inversions
c) More efficient in practice than most other
simple quadratic (i.e., O(n2)) algorithms such
as selection sort or bubble sort; the best case
(nearly sorted input) is O(n)
d) Stable; i.e., does not change the relative order
of elements with equal keys
e) In-place; i.e., only requires a constant amount
O(1) of additional memory space
f) Online; i.e., can sort a list as it receives it
When humans manually sort something (for
example, a deck of playing cards), most use a
method that is similar to insertion sort.
For example: - The following table shows the steps
for sorting the sequence {3, 1, 4, 1, 5, 9, 2, 6, 5, 4}.
In each step, the item under consideration is boxed.
The item that was moved (or left in place because it
was biggest yet considered) in the previous step is
shown in bold.
3 1 4 1 5 9 2 6 5 4
i = 10
3 1 4 1 5 4 2 6 5 9
i = 9
3 1 4 1 5 4 2 5 6 9
i = 8
3 1 4 1 5 4 2 5 6 9
i = 7
3 1 4 1 2 4 5 5 6 9
i = 6
3 1 4 1 2 4 5 5 6 9
i = 5
3 1 2 1 4 4 5 5 6 9
i = 4
1 1 2 3 4 4 5 5 6 9
i = 3
1 1 2 3 4 4 5 5 6 9
i = 2
1 1 2 3 4 4 5 5 6 9


Explain bubble sorting technique with an example.
Bubble sort, sometimes incorrectly referred to as
sinking sort, is a simple sorting algorithm that
works by repeatedly stepping through the list to be
sorted, comparing each pair of adjacent items and
swapping them if they are in the wrong order. The
pass through the list is repeated until no swaps are
needed, which indicates that the list is sorted. The
algorithm gets its name from the way smaller
elements "bubble" to the top of the list. Because it
only uses comparisons to operate on elements, it is
a comparison sort. Although the algorithm is
simple, most of the other sorting algorithms are
more efficient for large lists.
For example: - The following table shows the steps
for sorting the sequence {9, 2, 6, 5, 4}. In each
step, the pair of items under consideration is boxed.
The bigger item that was moved in the previous
step is shown in bold.
9 2 6 5 4
i = 5
2 9 6 5 4
i = 4
2 6 9 5 4
i = 3
2 6 5 9 4
i = 2
2 6 5 4 9


Debugging is the process of executing a program
with simple data sets to determine if the results are
satisfactory.

Explain Straight selection sorting technique with an
example.
The simplest of the selection sorts is called straight
selection. To illustrates how straight selection
works. In the version shown, the sorted list is
constructed from the right (i.e., from the largest to
the smallest element values).
3 1 4 1 5 9 2 6 5 4
i = 10
3 1 4 1 5 4 2 6 5 9
i = 9
3 1 4 1 5 4 2 5 6 9
i = 8
3 1 4 1 5 4 2 5 6 9
i = 7
3 1 4 1 2 4 5 5 6 9
i = 6
3 1 4 1 2 4 5 5 6 9
i = 5
3 1 2 1 4 4 5 5 6 9
i = 4
1 1 2 3 4 4 5 5 6 9
i = 3
1 1 2 3 4 4 5 5 6 9
i = 2
1 1 2 3 4 4 5 5 6 9

Figure: Straight Selection Sorting
At each step of the algorithm, a linear search of the
unsorted elements is made in order to determine the
position of the largest remaining element. That
element is then moved into the correct position of
the array by swapping it with the element which
currently occupies that position.
For example, in the first step shown in above
figure, a linear search of the entire array reveals
that 9 is the largest element. Since 9 is the largest
element, it belongs in the last array position. To
move it there, we swap it with the 4 that initially
occupies that position. The second step of the
algorithm identifies 6 as the largest remaining
element and moves it next to the 9. Each
subsequent step of the algorithm moves one
element into its final position. Therefore, the
algorithm is done after n-1 such steps.

Trace out the algorithm Merge Sort on the data set
{1,5,2,19,4,17,45,12,6}
Steps to perform Merge Sort on the data set
{1,5,2,19,4,17,45,12,6} are:
(1,5,2,19,4}{17,45,12,6)
((1,5,2) (19,4)) ((17,45)(12,6))
(((1,5) (2))((19)(4))) (((17)(45)) ((12) (6)))
((((1)(5))(2))((19)(4)))(((17)(45))((12)(6)))
(1,5) (2) (4,19) (17,45) (6,12)
(1,2,5) (4,19) (17,45) (6,12)
(1,2,4,5,19) (6,12,17,45)
(1,2,4,5,6,12,17,19,45)

Trace out the algorithm Quick Sort on the data set
{12,1,5,7,19,15,8,9,10}.
Steps to perform Quick Sort on the data
set{12,1,5,7,19,15,8,9,10} are:
{(12),1,5,7,19,15,8,9,10}
{(12),1,5,7,10,15,8,9,19}
{(12),1,5,7,10,9,8,15,19}
{8,1,5,7,10,9,(12),15,19}
{(7),1,5,8,10,9}{12}{(15),19}
{5,1,(7),8,10,9}{12}{15,19}
{(5),1}{7}{(8),10,9}{12}{15}{19}
{1,(5)}{7}{(8),9,10}{12}{15}{19}
{1,(5)}{7}{(8),9,10}{12}{15}{19}
{1}{5}{7}{8}{(9),10}{12}{15}{19}
{1}{5}{7}{8}{9}{10}{12}{15}{19}

Trace out the algorithm MaxMin on a data set
consisting of at least 8 elements.
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.

Give an algorithm to solve sum of first N integers
using recursion
Algorithm: SumPosInt
Input: n, the upper limit
Output: Sum of first n positive integers
Method:
if (n <= 0) // We only want positive integers
return 0;
else
if (n == 0) // We only want positive integers
return 1;
else
return (n + SumPosInt( n 1 ); // recursive step
if end
if end
Algorithm ends

What is recursion? Give an algorithm to solve
factorial of a number using recursion and iteration.
What are its merits and demerits? What is the
difference between recursion and iteration?
Recursion refers to the technique of defining a
process, problem and objects in terms of itself. It is
used to solve complex programming problems that
are repetitive in nature.
Merits of recursion are:
Mathematical functions, such as Fibonacci series
generation can be easily implemented using
recursion as compared to iteration technique.
In iterative technique looping of statements is very
much necessary.
Demerits of recursion are:
The recursive programs take considerably more
storage and take more time during processing.
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.
A recursive procedure can be called from within or
outside itself and to ensure its proper functioning it
has to save the return addresses in some order so
that, a return to the proper location will result when
the return to a calling statement is made.
The recursive programs needs considerably more
storage and will take more time.
Difference between recursion and iteration:
Recursion is a top down approach of problem
solving. It divides the problems into parts and
selects a key step postponing the rest whereas
iteration is a bottom up approach of solving
problem. An iterative approach begins with what is
known and this constructs the solution step by step.
Algorithm: Factorial (recursion)
Input: n, the integer value whose factorial is to be
computed
Output: factorial of n
Method: if (n==1) then
Return (l)
Else Return (n * factorial (n-1)
If end
Algorithm ends
Algorithm: factorial (iteration)
Input: n, number whose factorial is to be
calculated
Output: factorial of n
Method:
fact=1
for (i=1 to n in steps of +1 do)
fact= fact *i
for end
Display fact.
Algorithm ends

State the Towers of Hanoi Problem and design an
algorithm to solve the Towers of Hanoi problems.
The Tower of Hanoi (also called the Tower of
Brahma or Lucas' Tower and sometimes
pluralized) is a mathematical game or puzzle. It
consists of three rods, and a number of disks of
different sizes which can slide onto any rod. The
puzzle starts with the disks in a neat stack in
ascending order of size on one rod, the smallest at
the top, thus making a conical shape.
The objective of the puzzle is to move the entire
stack to another rod, obeying the following simple
rules:
Only one disk may be moved at a time.
Each move consists of taking the upper disk from
one of the stacks and placing it on top of another
stack.
No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven
moves. The minimum number of moves required to
solve a Tower of Hanoi puzzle is 2
n
- 1, where n is
the number of disks.

The following algorithm can be used to move the
top n discs from the first pin START to the final
pin Finish through the temporary pin TEMP.
MOVE (n, START, FINISH, TEMP)
1. When n = 1;
a. MOVE a disc from START to FINISH.
b. Return
2. Move the top n -1 discs START to TEMP using
FINISH as intermediary
[MOVE (n -, START, FINISH, TEMP)]
3. MOVE top disc from START to FINISH.
4. Move the top n -1 discs TEMP to FINISH using
START as intermediary
[MOVE (n -, START, FINISH, TEMP)]

The no. of levels in a tree is called depth.

(l+1/2
l+1
-1) is worst possible utilization in the
single dimensional array representation.

Sorting arrange the items in a set according to
predefined ordering relation.

The data structure used by recursive algorithms is
Stack.

Stack works on the strategy of first in first out.
False

What is a binary tree? What are the properties of a
binary tree? Mention its applications.
A binary tree is made up of nodes where each node
consists of three elements, left node, right node and
a data element. The root node is the topmost node
of the binary tree.
Property of binary tree:
1. A node has a parent known as root node.
2. A node may have two children.
3. The distance of node from root is called level.
4. Root always lies at level 0.
5. If a node is at level l then its children will at
level l+1.
6. Maximum number of level is called depth.
7. Maximum number of node in a binary tree of
depth will be 2d-1
Application of binary tree:
There are several applications of binary tree. Few
of them are as following:
1. Indexing
2. Encoding messages using Huffman tree
3. Arithmetic expression evaluation

Differentiate between complete and full binary
trees?
The following table lists the differences between
complete binary trees and full binary trees:
Complete binary trees
All the nodes at the previous level are fully
accommodated before the next level is
accommodated.
Number of nodes at the last (n) level may or may
not equal to 2
n
.
Leaf nodes may or may not be at the same level.
A complete binary tree may or may not be full
binary tree.
Full binary trees
All levels are maximally accommodated.
Number of nodes at the last (n) level is exactly
equal to 2n.
All leaf nodes are at the same level.
A full binary tree is always a complete binary
tree.

What is the maximum number of nodes in the
binary tree of level 7, 8, and 9?
The maximum number of nodes in the binary tree
is calculated by 2
l+1
- 1 where l is the level of the
binary tree.
The maximum number of nodes for level 7, 2
7+1
- 1
= 255
The maximum number of nodes for level 8, 2
8+1
- 1
= 511
The maximum number of nodes for level 9, 2
9+1
- 1
= 1023

What is the wastage of memory for a binary tree
with 16 nodes represented in a 1D array, 2D array,
and a linked representation?
a) For a 1D array, the formula for calculating
percentage of memory utilization is:
(n -1/2
l+1
- 1)*100 where n represents the number
of nodes and l represents the depth of the tree.
However, in the given question, the depth has not
been specified. Therefore, the percentage memory
utilization cannot be calculated.
b) For a 2D array, the percentage of memory
utilization is:
(n -1/n
2
)*100 = (16 -1/16
2
)*100 = 5.86%
Therefore, the wastage of memory in 2D array is
100 - 5.86 = 94.14%
c) For a linked list, the percentage of memory
utilization is:
(n -1/2n)*100 = (16 -1/2*16)*100 = 46.88%
Therefore, the wastage of memory in 1D is 100 -
46.88 = 53.13%

For at least 5 binary trees of different depths
greater than or equal to 6 of your choice, obtain the
preorder, postorder and inorder sequences.
The following figure shows a binary tree with 14
nodes where A is the root node:

Binary Tree with 14 Nodes
The preorder traversal sequence for the above
binary tree is: ABDHKMNLECFIJG
The inorder traversal sequence for the above
binary tree is: MKNHLDBEAIFJCG
The postorder traversal sequence for the above
binary tree is: MNKLHDEBIJFGCA

Proved that there are n+ 1 null pointer in linked
representation a binary tree of n nodes.
In a binary tree of N nodes, if all of the nodes have
one pointer set to null, then the tree is completely
unbalanced, and has the characteristics and
performance of a linked list. If you have N+1 null
pointer, then the extra node is a special "head"
node used to simplify processing of the tree. That
"head" node will always have one pointer set to
null.

The percentage of memory wastage in linked
representation of binary tree is 50%.
Explained linked representation of a binary tree
with its typical node structure.)
Given Linked List Representation of Complete
Binary Tree, construct the Binary tree. A complete
binary tree can be represented in an array in the
following approach.
If root node is stored at index i, its left, and right
children are stored at indices 2*i+1, 2*i+2
respectively.
Suppose tree is represented by a linked list in same
way, how do we convert this into normal linked
representation of binary tree where every node has
data, left and right pointers? In the linked list
representation, we cannot directly access the
children of the current node unless we traverse the
list.

We are mainly given level order traversal in
sequential access form. We know head of linked
list is always is root of the tree. We take the first
node as root and we also know that the next two
nodes are left and right children of root. So we
know partial Binary Tree. The idea is to do Level
order traversal of the partially built Binary Tree
using queue and traverse the linked list at the same
time. At every step, we take the parent node from
queue, make next two nodes of linked list as
children of the parent node, and enqueue the next
two nodes to queue.
1. Create an empty queue.
2. Make the first node of the list as root, and
enqueue it to the queue.
3. Until we reach the end of the list, do the
following.
a. Dequeue one node from the queue. This is the
current parent.
b. Traverse two nodes in the list, add them as
children of the current parent.
c. Enqueue the two nodes into the queue.

Explain expression tree.
A binary expression tree is a specific application of
a binary tree to evaluate certain expressions. Two
common types of expressions that a binary
expression tree can represent are algebraic and
Boolean. These trees can represent expressions that
contain both unary and binary operators.
In general, expression trees are special kind of
binary trees. A binary tree is a tree in which all
nodes contain zero, one or two children. This
restricted structure simplifies the programmatic
processing of Expression trees.
The leaves of a binary expression tree are
operands, such as constants or variable names, and
the other nodes contain operators. These particular
trees happen to be binary, because all of the
operations are binary, and although this is the
simplest case, it is possible for nodes to have more
than two children. It is also possible for a node to
have only one child, as is the case with the unary
minus operator. An expression tree, T, can be
evaluated by applying the operator at the root to the
values obtained by recursively evaluating the left
and right subtrees.
Traversal
An algebraic expression can be produced from a
binary expression tree by recursively producing a
parenthesized left expression, and then printing out
the operator at the root, and finally recursively
producing a parenthesized right expression. This
general strategy (left, node, right) is known as an
in-order traversal. An alternate traversal strategy is
to recursively print out the left subtree, the right
subtree, and then the operator. This traversal
strategy is generally known as post-order traversal.
A third strategy is to print out the operator first and
then recursively print out the left and right subtree.
These three standard depth-first traversals are
representations of the three different expression
formats: infix, postfix, and prefix. An infix
expression is produced by the inorder traversal, a
postfix expression is produced by the post-order
traversal, and a prefix expression is produced by
the pre-order traversal.
Algebraic expressions
Algebraic expression trees represent expressions
that contain numbers, variables, and unary and
binary operators. Some of the common operators
are (multiplication), (division), + (addition),
(subtraction), ^ (exponentiation), and - (negation).
The operators are contained in the internal nodes of
the tree, with the numbers and variables in the leaf
nodes. The nodes of binary operators have two
child nodes, and the unary operators have one child
node.
Boolean expressions
Boolean expressions are represented very similarly
to algebraic expressions, the only difference being
the specific values and operators used. Boolean
expressions use true and false as constant values,
and the operators include (AND), (OR), (NOT).

The percentage of memory wastage in adjacency
matrix representation of binary tree is 1/nX100.

A binary tree of depth d has almost 2
d
-1 number of
nodes.

Explain decision tree.
A decision tree is a flowchart-like structure in
which internal node represents test on an attribute,
each branch represents outcome of test and each
leaf node represents class label (decision taken
after computing all attributes). A path from root to
leaf represents classification rules.
In decision analysis a decision tree and the closely
related influence diagram is used as a visual and
analytical decision support tool, where the
expected values (or expected utility) of competing
alternatives are calculated.
A decision tree consists of 3 types of nodes:
1. Decision nodes - commonly represented by
squares
2. Chance nodes - represented by circles
3. End nodes - represented by triangles
Decision trees are commonly used in operations
research, specifically in decision analysis, to help
identify a strategy most likely to reach a goal. If in
practice decisions have to be taken online with no
recall under incomplete knowledge, a decision tree
should be paralleled by a probability model as a
best choice model or online selection model
algorithm. Another use of decision trees is as a
descriptive means for calculating conditional
probabilities.
Decision trees, influence diagrams, utility
functions, and other decision analysis tools and
methods are taught to undergraduate students in
schools of business, health economics, and public
health, and are examples of operations research or
management science methods.
Decision trees are commonly used in operations
research, specifically in decision analysis, to help
identify a strategy most likely to reach a goal.
Advantages and disadvantages
Amongst decision support tools, decision trees (and
influence diagrams) have several advantages.
Decision trees:
1. Are simple to understand and interpret. People
are able to understand decision tree models after a
brief explanation.
2. Have value even with little hard data. Important
insights can be generated based on experts
describing a situation (its alternatives, probabilities,
and costs) and their preferences for outcomes.
3. Possible scenarios can be added
4. Worst, best and expected values can be
determined for different scenarios
5. Use a white box model. If a given result is
provided by a model.
6. Can be combined with other decision techniques.
The following example uses Net Present Value
calculations, PERT 3-point estimations (decision
#1) and a linear distribution of expected outcomes
(decision #2):
Disadvantages of decision trees:
1. For data including categorical variables with
different number of levels, information gain in
decision trees are biased in favor of those attributes
with more levels.
2. Calculations can get very complex particularly if
many values are uncertain and/or if many outcomes
are linked.

Design recursive algorithms to traverse a binary
tree represented in linked lists in inorder, preorder
and postorder and hand simulate your algorithm
with an example.
Algorithm : Inorder Traversal
Input: bt, address of root node.
Output : Inorder sequence
Method:
If(bt!=null)
{Inorder ([bt].Lchild)
Display [bt].data
Inorder ([bt].Rchild)}
Algorithm ends

Algorithm : Preorder Traversal
Input: bt, address of root node.
Output : Preorder sequence
Method:
If(bt!=null)
{Display [bt].data
Preorder ([bt].Lchild)
Preorder ([bt].Rchild)}
Algorithm ends

Algorithm : Postrder Traversal
Input: bt, address of root node.
Output : Postorder sequence
Method:
If(bt!=null)
{Postorder ([bt].Lchild)
Postorder ([bt].Rchild)
Display [bt].data }
Algorithm ends







Post order traversal of above tree: EFLBCA
Pre order traversal of above tree: ABDEFC
In order traversal of above tree: EDFBAC

One of the properties of an algorithm is beauty.
False

A graph without self-loop and parallel edges is
simple graph.
What are the limitations of linear queue? How do
you overcome using circular queue?
Limitation of linear queue is that it does not make
most use of available memory. It may show queue
is full even when there is memory space is
available. If we have inserted element at the last
index and there is space available then also we
cannot insert element. We can overcome this
limitation using circular queue because circular
queue makes more utilization of memory. In a
circular queue if we inserted element at the last
index and if there is space available then we can
insert element in a circular queue.

Design an iterative algorithm to traverse a binary
represented in two dimensional matrixes.
Algorithm: Traversing a binary tree represented in
two dimensional matrix
Locate the root.
Display
Push into stack
Scan the row in search of L for left child element
Pop from the stack
Decision tree
Check if array IsEmpty()
Stop

Write a program to sort a list strings using bubble
sort technique?
class bubble_sort
{
static String arr[]={"ramesh", "dinesh", "suresh",
"naresh"};
public static void main(String args[])
{
String temp;
{
for(int i=0; i<(arr.length); i++)
{
for(int j=i+1; j<arr.length; j++)
{
if(arr[i].compareTo(arr[j])>0)
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
} }
System.out.println(arr[i]);
} } } }

Write a program to find the roots of a quadratic
equation.
Algorithm: Quadratic_Solver
Input: a, b, c the co efficient of Quadratic
Equation
Output: two roots of quadratic equation
Method:
disc= (( b*b)-4*a*c))
if (disc=0)
Display roots are real and equal.
R1b/2a
R2=-b/2a
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 parts, -b/2a
Display imaginary parts,sqrt(absolute_value_of
(disc))
Display two roots exists in conjugates
End if
Algorithm ends

Design an iterative and recursive algorithm to find
the minimum among n elements.
Algorithm: Minimum Finder
Input: n, size of array
A, array of n elements
Output: return the minimum value.
Method:
Display enter the size of array.
Accept n
Display enter element one by one.
For (i= 1 to n in steps of+1 do)
Accept A[i]
For end
min=A[1]
for (i=2 to n in steps of +1 do)
if(A[i]<min)
min=A[i]
if end
for end
Display min.
Algorithm ends

Write an algorithm to sort the list of numbers using
selection sort
Algorithm: Selection Sort
Input: n, size of array
A, array of size n
Output: A, sorted list
Method:
for (i=1 to n in steps of +1 do)
j=i
for ( k=i+1 in steps of +1 do)
if (A[k]<A[j])
j=k
if end
for end
Interchange A[i] and A[j]
for end.
Algorithm ends.
Write an iterative and recursive algorithm to search
for an element using binary search technique.
Algorithm: Binary Search (Iterative Method)
Input: A, size of array
K, search element
Output: low index of k
Method:
low=1
high=n
While(low<=high)
{
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)
exits(); }
Else
write(search unsuccessful)
if ends;
Algorithm ends

Algorithm: Binary Search (Recursive method)
Input: A, array of n element
K, search element
low, lower limit
high, upper limit
Output: index of K is returned
Method:
if(low<=high)
mid=(low+ high)/2
if(A[mid]=K)
return mid
else
if(k<A[mid])
Binary Search (A, k, low, mid-1)
else
Binary Search (A, k, mid+1, high)
if end
if end
else
Return 0
if end
Algorithm ends

Design the recursive algorithm to sort a list of
elements using merge sort and hand simulate a
dataset of at least 9 elements.
Algorithm: MergeSort
Input: low, high, the lower and upper limit of the
list to be sorted.
A, list of elements
Output: A, sorted list
Method:
If(low<high)
MergeSort(low, mid)
MergeSort(mid, high)
Merge(A,low,mid,high)
If end
Algorithm ends

Algorithm : Merge
Input: low, mid, high limits of two list to be
merged.
Output : B, the merged list
Method:
h=low
i=low
j=mid+1
while((h<=mid) and(j<=high))
if(A[h]<=A[j])
B[i]=A[h]
h=h+1
else
B[i]=A[j]
j=j+1
if end
i=i+1
if(h>mid)
for(k=j to high)
B[i]=A[k]
I=i+1
for end
else
for(k=h to mid)
B[i]=A[k]
i=i+1
for end
if end
while end
Algorithm ends

Recursion is a technique of defining a process by
itself.

A tree is a connected graph without any circuit.












Design an iterative and recursive algorithm to
generate Fibonacci sequence of length n.
Algorithm: Fibonacci Series (Iterative Approach)
Input: n, the number of elements in series
Output: Fibonacci series up to n elements
Method:
a=-1
b=1
For (i=1 to n in steps of +1 do)
c=a+b
Display c.
a=b
b=c
for end
Algorithm ends
Algorithm: Fibonacci Series (Iterative Approach)
Input: n, the number of elements in series
Output: Fibonacci series up to n elements
Method:
If (n=1)
Return (1)
Else
If (n=2)
Return (2)
Else
Return (Fibonacci (n-1) + Fibonacci (n-2))
If end
If end
Algorithm ends

Selection Sort Algorithm
Algorithm: selection sort
Input: n, a[1..n]
Output: a[1..n] to be sorted
Method:
for i=1 to n-1 in steps of +1
j=i
for k=i+1 to n in steps of +1
if(a[k]<a[j])
j=k
for end
interchange a[i] and a[j]
for end
Algorithm ends

Quick Sort Algorithm
Algorithm: quicksort
Input: p,q the lower limit and upper limits of the
list of array A
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
Algorithm ends

Partition Algorithm
Algorithm: partition
Input: 1. m, the position of the element whoose
actual position in the sorted list has to be found 2.
P, the upper limit of the list
Output: the position of m element
Method:
v=a[m]
i=m
repeat
repeat i= i+1 until(a[i]>=v)
repeat p=p-1 until(a[p]<=v)
if(i<p)
interchange a[i] and a[p]
if end
until(i>=p)
a[m]=a[p]
a[p]=v
Algorithm ends

Write recursive algorithm to find the GCD of two
numbers.
Algorithm: GCD
Input: dv, number(divisor)
dd, number(divider)
rem, number(remainder)
Output: return the GCD
Method gcd (dd, dv)
Rem=dd% dv
if rem == 0
display dv
else
Interchange (dd = dv)
(dv=rem)
gcd(dd, dv)
if end
Algorithm ends

Design an algorithm to check the graph connected.
Algorithm: Graphconnectivity_Testing
Input: pathbv, Boolean
Path, test condition
Output: Path updated
Method:
if(path=1)
Pathbv = true
Display Graph is connected
else (path=0)
Path=false
Display Graph is not connected
end if
Algorithm ends




Two matrices that have the same number of rows
and columns can be multiplied to produce a third
matrix. Consider the following two matrices.
11 12 1n 11 12 1n
21 22 2n 21 22 2n
n1 n2 nm n1 n2 nm
a a ............. a b b ............. b
A a a ............. a B b b ............. b
a a ............. a b b ............. b






The product of A and B is a third matrix C of size b
by n where each element of C is given by the
following equation.
n
ij 1k kj
k 1
C a b



Write a program that will read the values of
elements of A and B and produce the product
matrix C.
import java.io.*;
class MatrixMult
{
int m=0;
int n=0;
int a[][]=new int[3][3];
int b[][]=new int[3][3];
int i=0;
int j=0;
int k=0;
int term;
public MatrixMult()
{ try {
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the value of m and n for a
matrix: \n");
System.out.print("\nm: ");
int m =Integer.parseInt(br.readLine());
System.out.print("\nn: ");
int n =Integer.parseInt(br.readLine());
System.out.print("\nEnter first matrix
elements(mxn)\n");
/* Input the first matrix */
for(i=0;i<m;i++)
{
System.out.print("\nEnter the row numbers:\n");
for(j=0;j<n;j++)
a[i][j] = Integer.parseInt(br.readLine()); }
System.out.print("\nEnter second matrix
elements(nxm)\n");
/* Input the second matrix */
for(j=0;j<n;j++)
{
System.out.print("\nEnter the row numbers:\n");
for(k=0;k<m;k++)
b[j][k] = Integer.parseInt(br.readLine()); }
/* Multiplication of two matrices */
System.out.print("\nMultiplication of the two
matrix is: \n\n");
term = 0;
for(i=0;i<m;i++)
{ for(k=0;k<m;k++)
{ term=0;
for(j=0;j<n;j++)
{ term = term + (a[i][j]*b[j][k]); // multiplication }
System.out.print("\t");
System.out.print(term);
System.out.print(" "); }
System.out.print("\n");
} }catch(Exception e)
{ System.out.println("Exception is :"+e);
} }
public static void main(String args[])
{ MatrixMult MM = new MatrixMult();
} }

Write a program to split a string into multiple java
string objects
public class MyStrSplit {
public static void main(String a[]){
String str = "This program splits a string based on
space";
String[] tokens = str.split(" ");
for(String s:tokens){
System.out.println(s);
}
str = "This program splits a string based on
space";
tokens = str.split("\\s+");
}
}

write a program to remove a leading thread and
trailing space from string using trim method of java
string class
import java.io.*;
public class RemoveLeadingTrailingSpace
{
public static void main(String[] args)
{
String str = " String Trim Example ";
String strTrimmed = str.trim();
System.out.println("Original String is: " + str);
System.out.println("Removed Leading and trailing
space");
System.out.println("New String is: " +
strTrimmed);
}
}

What is a Thread?
In a thread based multitasking environment, thread
is the smallest unit of dispatchable code. A Thread
is a single stream of execution within a process.
This means that a single program can perform two
or more tasks simultaneously. For instance a text
editor can format text at the same time that it is
printing.
Assume that a bank maintains two kinds of account
for its customers, one called savings account and
the other current account. The savings account
provides compound interest and withdrawal
facilities but no cheque book facility. The current
account provides cheque book facility but no
interest. Current account holders should also
maintain a minimum balance and if the balance
falls below this level, a service charge is imposed.
Create a class Account that stores customer name,
account number and the type of account. From this
derive the classes Curr-acct and Sav-acct to make
them more specific to their requirements. Include
the necessary methods in order to achieve the
following tasks:
import java.io.*;
class Account{
String custName;
String accNo;
String amount;
double balance;
public void input(){
try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Name of a Account
Holder");
custName=br.readLine();
System.out.println("Enter the Account Number of a
Account Holder");
accNo=br.readLine();
System.out.println("Enter the Amount to be
deposited");
amount=br.readLine();
balance=Double.parseDouble(amount);
}
catch(Exception g){}
}
public void deposit(){
try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Amount to be
deposited");
amount=br.readLine();
double amt=Double.parseDouble(amount);
balance=balance+amt;
System.out.println("Balance: "+balance);
}
catch(IOException e){}
}
public void withdraw() {
try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Amount to be
withdrawl");
amount=br.readLine();
double amt=Double.parseDouble(amount);
balance=balance-amt;
System.out.println("Balance: "+balance);
}
catch(IOException e){}
}
public void display(){
System.out.println("Account Holder Details");
System.out.println("----------------------");
System.out.println("Name: "+custName);
System.out.println("Balance: "+balance);
}
}
class Current extends Account{
public void chequebook(){
if(balance<1000)
System.out.println("Cheque book has not been
issued");
else
System.out.println("Cheque book has been
issued");
}
public void minimumBal(){
double penalty=1000;
if(balance < 10000){
balance=balance-penalty;
} }
public void display(){
minimumBal();
super.display();
}
}
public class Saving extends Account{
public void calInterest(){
double interest=0;
System.out.println(interest);
balance=balance*Math.pow(1.05, 2);
System.out.println(balance);
}
public void display(){
calInterest();
System.out.println(balance);
super.display();
}
public char menu(){
char choice='a';
System.out.println("Menu");
System.out.println("1. Current Account");
System.out.println("2. Savings Account");
System.out.println("3. Exit");
System.out.println("Enter your choice(1-3)");
try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
choice=(char)br.read();
}
catch(Exception e){
System.out.println("Error");
}
if (choice =='3'){ System.exit(0);}
return choice; }
public static void main(String a[]){
char choice;
Saving o=new Saving();
while(true){
choice = o.menu();
try{
switch(choice)
{
case '1':
Current object=new Current();
while(true){
System.out.println("Menu");
System.out.println("1. Enter Details");
System.out.println("2. Deposit Amount");
System.out.println("3. Withdraw Amount");
System.out.println("4. Display Balance");
System.out.println("5. Issue ChequeBook");
System.out.println("6. Exit");
try{ System.out.println("Enter your choice(1-6)");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
char ch=(char)br.read();
switch(ch){
case '1':
object.input();
break;
case '2':
object.deposit();
break;
case '3':
object.withdraw();
break;
case '4':
object.display();
break;
case '5':
object.chequebook();
break;
case '6':
choice = o.menu();
default:
System.out.println("Please Enter the valid choice");
break;
} }catch(IOException e){} }
case '2':
Saving object1=new Saving();
while(true){
System.out.println("Menu");
System.out.println("1. Enter Details");
System.out.println("2. Deposit Amount");
System.out.println("3. Withdraw Amount");
System.out.println("4. Display Balance");
System.out.println("5. Exit");
try{ System.out.println("Enter your choice(1-4)");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
char ch=(char)br.read();
switch(ch){
case '1':
object1.input();
break;
case '2':
object1.deposit();
break;
case '3':
object1.withdraw();
break;
case '4':
object1.display();
break;
case '5':
o.menu();
default:
System.out.println("Please enter the valid choice");
break;
} }
catch(Exception e){} }
case '3':
System.out.println("Please enter the valid choice");
System.exit(0);
break;
} }
catch(Exception e){} } } }

How does String class differ from the StringBuffer
class?
String class has a limit while there is no limit in
StringBuffer class. In the StringBuffer class input
is flushed while it is not so in the String class.
String is an array whose all elements are of
character type. String class is used in the same
manner that we might use any other predefined
class. For example we might declare an instance of
the String class as follows:
String name = new String();

What is Synchronization? Why do we use it?
Multithreading introduces a synchronous behavior
in programs. There is a need to enforce
synchronicity when it is necessary. For example, if
two threads are to communicate and share a data
structure, there is a need to avoid conflict between
them. That is, a thread must be prevented from
writing data while the other thread is reading the
data.
To overcome this problem, Java implements a
model of interprocess communication called
monitor. The monitor is a control mechanism that
can hold only one thread at a time. Once a thread
enters a monitor, all other threads have to wait until
that exits from the monitor.
How is a thread created?
Threads are implemented in the form of objects
that contain a method called run( ). The run()
method makes up the entire body of the thread. A
typical run( ) would appear as follows:
public void run() {
----------------
--------------- (Statements for
implementing thread)
---------------
}
The run() method should be invoked by an object
at the concerned thread.
A new thread can be created in two ways:
Define a class that implements Runnable interface.
Define a class that extends Thread class.

What is an exception?
An exception is a run time error. Most of the
computer languages do not support exception
handling. Errors must be checked and handled
manually. This is cumbersome and troublesome.
Java provides the facility of exception handling and
avoids the above problems. By this run time error
management becomes easy.
A Java exception is an object that describes an
error condition that has occurred in a piece of code.
When an error or an exceptional condition arises,
an object representing that exception is created and
is 'thrown' in the method that caused the error. The
method may handle the exception itself or pass it
on. In this way, the exception is caught and
processed. Exceptions thrown by Java relate to
fundamental errors that violate the rules of the
language.

How do we define a try block?
The programmer encloses in a try block the code
that may generate an exception. The try block is
immediately followed by zero or more catch
blocks. Each catch block specifies the type of
exception it can catch and contains an exception
handler.
When an exception is thrown, program control
leaves the try block and catch blocks are searched
for an appropriate handler.
For example, the following code defines a try
block.
try {
d=0;
a=42/d;
System.out.println(*This will not be printed,*); }

How do we define a catch block?
The 'try' block is immediately followed by zero or
more catch blocks. Each catch block specifies the
type of exception it can catch and contains an
exception handler.
When an exception is thrown, program control
leaves the try block and catch blocks are searched
for an appropriate handler.
For example, the following code defines a try-catch
block.
try { d=0;
a=42/d;
System.out.println(*This will not be printed,*); }
catch(ArithmeticException e)
{ System.out.println("Division by zero"); }

How many catch blocks can we use with one try
block?
The try block is immediately followed by zero or
more catch blocks. It means you can use as many
catch blocks with one try block. But there must be
at least one catch block following a try block,
unless you are using a finally block.
For example, consider the following program:
Class Exception {
Public Static void main(string args[ ] ){
int d,a;
try { d=0;
a=42/d;
System.out.println(*This will not be printed,*);
} catch(Arithmetic Exception) {
error System.out.println(*Division by Zero*);}
System.out.println(*After catch statement.*);} }
This program generates the following output
Division by Zero.
After Catch Statement.

What is a finally block? When and how is it used?
Give a suitable example.
After the last catch block, an optional finally block
provides code that always executes regardless of
whether or not an exception occurs. If there are no
catch blocks following a try block, the finally block
is required.
If a finally block appears after the last catch block,
it is executed regardless of whether or not an
exception is thrown.
For example, the following program shows the use
of a finally block.
class finaldemo
{ static void A()
{ try
{ System.out.println( "now in A");
throw new RuntimeException("demo");}
finally
{ System.out.println("finalA"); } }
public static void main(String args[])
{ try
{ A();d}
catch( Exception e)
{ System.out.println("exc caught");
} } }
Write the algorithms to perform different
operations on a circular queue.
Algorithm: Create
Output: CQ, Circular Queue created
Method:
Declare CQ[Size]
Declare R and initialize R=0
Declare F and initialize F=0
Algorithm ends

Algorithm: Isempty
Input : CQ, circular queue
Output: Boolean
Method:
If(F=0)
Return true
Else
Return false
If end
Algorithm ends

Algorithm: Isfull
Input : CQ, circular queue
Output: Boolean
Method:
If(R=Size)
Return true
Else
Return false
If end
Algorithm ends

Algorithm: Front
Input: CQ, circular queue
Output : return front element
Method:
If(f=0)
Print no front element
Else
Return CQ[F]
If end
Algorithm ends

Algorithm: Rear
Input: CQ, circular queue
Output : return rear element
Method:
If(f=0)
Print no back element
Else
Return CQ[R]
If end
Algorithm ends

Algorithm: insertion
Input: CQ, circular queue
e, element to be inserted
F, front pointer
R, rear pointer
SIZE, size of circular queue
Output: F, R and CQ updated
Method:
If(Is full(CQ))then
Print Overflow
Else
R=R mod SIZE +1
CQ[R]=e
If(F=0)
F =1
If end
If end
Algorithm ends

Algorithm: deletion
Input: CQ, circular queue
e, element to be deleted
F, front pointer
R, rear pointer
SIZE, size of circular queue
Output: F, R and CQ updated
Method:
If(Is empty(CQ))then
Print empty
Else
e=CQ[F]
if(F=R)
F=R=0
Else
F=F mod SIZE+1
If end
If end
Algorithm ends

Design algorithm to search an element for its
presence/absence in a given list of random data
elements without sorting the list.
Algorithm: Presence_Absence Test
Input: n, size of array
A, array of n size
K, search element
Output: return index of k
Method:
i =1
while (i<=n)
if (k=A[i])
k is at index i.
exit();
else
i++;
if end
while end.
Display Search Unsuccessful.
Algorithm ends

Explain and illustrate insertion sort algorithm to
sort a list of n numbers.
Algorithm: Insertion Sort
Input: n, size of array
A[1n] array of n element
Output: A[1.n] sorted
Method:
For(j=2 to n in steps of +1 do)
Item=A[j]
i=j-1
while((i>=1) and (item<A[i])
A[i+1]=A[i]
i=i-1
end while
A[i+1]=item
end for
Algorithm ends

Hand simulation of insertion sort:
Consider an array of size n=5 whose elements are
2, 5, 6, 7, 3
Outer loop started:
j=2 (is j<=n) i.e. is (2<=5) yes
item = A[j] i.e. item= A[2]=5
i=j-1 i.e. i=2-1=1
inner while loop started:
is((i>=1) and(item<A[i]))
i.e. is((1>=1) and(5<2)) no
out of inner loop
A[i+1]=item i.e. A[1+1]=5 i.e store5 at index A[2].
Array becomes: 2, 5, 6, 7, 3
j=3 (is j<=n) i.e. is(3<=5) yes
Item= A[j] i.e. item= A[3]=6
i=j-1 i.e. i=3-1=2
Inner while loop started:
is((i>=1) and (item<A[i]))
i.e. is((2>=1) and(5<A[3]))
i.e. is((2>=1) and(5<6)) no
out of inner while loop
A[i+1]=item i.e. A[2+1]=6 i.e store6 at index A[3].
Array becomes: 2, 5, 6, 7, 3
j=4 is(j<=n) i.e. is(4<=5) yes
item= A[j] i.e. item=A[4] i.e. item=7
i=j-1 i.e. i=4-1=3
inner while loop started:
is((i>=1) and (item<A[i]))
i.e. is((3>=1) and(7<A[3]))
i.e. is((3>=1) and(7<6)) no
out of inner while loop
A[i+1]=item. i.e. A[3+1]=7 i.e. store 7 at index
A[4]
Array becomes: 2, 5, 6, 7, 3
j=5 is(j<=n) i.e. is(5<=5) yes
item=A[j] i.e. item=A[5] i.e. item=3
i=j-1 i.e. i=5-1=4
inner loop started:
is((i>=1)and (item<A[i]))
i.e. is ((4>=1) and(3<7)) yes
A[i+1]=A[i] i.e. A[4+1]=A[4] i.e. store A[4] at
index A[5].
Array becomes: 2, 5, 6, 7, 7
i=i-1 i.e. i=4-1=3
is((i>=1) and (item<A[i])) i.e. is((3>=1)
and(3<A[3]))
i.e. is((3>=1) and(3<6)) yes
A[i+1]=A[i] i.e. A[3+1]=A[3] i.e. store A[3] at
index A[4].
Array becomes: 2,5,6,6,7
i=i-1 i.e. i=3-1=2
is((i>=1) and(item<A[i])) i.e. is((2>=1)
and(3<A[2]))
i.e. is((2>=1) and(3<5)) yes
A[i+1]=A[i] i.e. A[2+1]=A[2] i.e. store A[2] at
A[3]
Array becomes: 2,5,5,6,7
i=i-1 i.e. i=2-1=1
is((i>=1) and(item<A[i])) i.e. is((1>=1)
and(3<A[1]))
i.e. is((1>=1) and(3<2)) no
out of inner while loop
A[i+1]=A[i] i.e. A[1+1]=item i.e. A[2]=3 i.e. store
3 at index A[2].
Array becomes 2,3,5,6,7
J=6 is(j<=n) i.e. is(6<=5) no
Out of outer for loop.
Sorted array : 2,3,5,6,7

Design an algorithm in iteration and recursion to
find minimum and maximum elements in n
elements.
Algorithm: MaxMin
Input: p.q, lower and upper limit of the list
Output: minimum and maximum numbers in a list
Method:
If(p=q)
max=A[p]
min=A[q]
else
if(p=q-1)
if(A[p]>A[q])
max=A[p]
min=A[q]
else
max=A[q]
min=A[p]
if end
else
m=(p + q)/2
MaxMin (p, m, max1, min1)
MaxMin (m+1, q, max2, min2)
max large (max1,max2)
min small (min1,min2)
if end
if end
Algorithm ends

Potrebbero piacerti anche