0% found this document useful (0 votes)
12 views26 pages

Daa Qnpaper

The document discusses various algorithmic concepts including recurrence relations, time and space complexity, and specific algorithms like brute force string matching and merge sort. It outlines the steps for dynamic programming, the fundamentals of algorithmic problem solving, and provides examples for recursive algorithms such as factorial calculation and binary search. Additionally, it covers the closest pair problem, convex hull problem, and the travelling salesman problem, along with their definitions, procedures, and time complexities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views26 pages

Daa Qnpaper

The document discusses various algorithmic concepts including recurrence relations, time and space complexity, and specific algorithms like brute force string matching and merge sort. It outlines the steps for dynamic programming, the fundamentals of algorithmic problem solving, and provides examples for recursive algorithms such as factorial calculation and binary search. Additionally, it covers the closest pair problem, convex hull problem, and the travelling salesman problem, along with their definitions, procedures, and time complexities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

2 MARKS

1.A recurrence relation is a mathematical expression that


defines a sequence in terms of its previous terms. In the
context of algorithmic analysis, it is often used to model the
time complexity of recursive algorithms.
General form of a Recurrence Relation: an=f(an−1,an−2,
….,an−k)
where f is a function that defines the relationship between
the current term and the previous terms
2.The efficiency of an algorithm is typically measured using
two main metrics: time complexity and space complexity.

3.Algorithm: Brute Force String Matching


Input: Text ( T ) of length ( n ) and pattern ( P ) of length ( m ).
Process:
For each position ( i ) in ( T ) from 0 to ( n - m ):
Compare ( P ) with the substring of ( T ) starting at ( i ).
If all characters match, return the starting index ( i ).
Output: Index of the first match or -1 if no match is found.
Example: For ( T = \text{“hello world”} ) and ( P = \
text{“world”} ), the output is 6.

4. The convex hull of a set of points is the smallest convex


polygon that can enclose all the points.
Example:
Input: Points ((0, 0)), ((0, 4)), ((-4, 0)), ((5, 0)), ((0, -6))
Output: Convex hull points ((-4, 0)), ((5, 0)), ((0, -6)), ((0, 4))
Visualization:
(0, 4) *
/\
/ \
(-4, 0) -------* (5, 0)
\ /
\/
* (0, -6)
5.Dynamic Programming Procedure
1.Define the State: Identify the state variables representing
subproblems.
2.Recurrence Relation: Establish how to compute the current
state using previous states.
3.Base Cases: Solve the simplest subproblems directly.
4.Compute Solution: Use either memoization (top-down) or
tabulation (bottom-up) to solve the problem.
PART B
6.) Discuss fundamentals of Algorithmic problem solving.
An algorithm is a finite set of instructions that accomplishes a
particular task.
An algorithm is the actual procedure to solve a particular
problem.
An algorithm is step by step procedure to solve a problem.

NOTION OF AN ALGORITHM
An algorithm is a sequence of non-ambiguous instructions for
solving a problem in a finite amount of time.
* An input to an algorithm specifies an instance of the
problem.
* An algorithm can be specified in a natural language or a
pseudo code.
* Algorithm can be implemented as computer programs.
Characteristics of an Algorithm
The important and prime characteristics of an algorithm are
1. Input
Zero (or) more quantities externally supplied.
2. Output
At least one quantity is produced.
3. Definiteness
Each instruction is clear and ambiguous.
4. Finiteness
The algorithm terminates after a finite number of steps.
5. Efficiency
Every instruction must be very basic.
6. Unambiguity
An algorithm must be expressed in a fashion that is
completely free of ambiguity.
Example 1
1. An algorithm to calculate simple interest
Step 1: Read the input values for principles (P),
No. of years (N), Rate (R)
Step 2: Compute SI = P*N* R
Step 3: Print SI
Step 4: Stop the process.
b.) Discuss the steps involved in mathematical analysis of
recursive algorithm. Do the same for finding factorial of N
numbers and binary search.
Recursive Algorithm
The algorithm executed recursively until it met a condition.
General Plan for Analyzing Efficiency of Recursive Algorithm
1. Decide on parameter indicating an input's size
2. Identify the algorithm's basic operation
3. Check whether the number of times the basic operation is
executed can vary on different inputs of the same size
4. Set up a recurrence relation, with an appropriate initial
condition for the number of times the basic operation is
executed.
5. Solve the recurrence equation.
Example 1
Find the factorial of a given n0

Algorithm F(n)
// Computes n! recursively.
// Input - A non negative integer n.
// Output -the value of n!
If (n = 0).
return 1
Inti
else
return F(n - 1)* n.
Formula
F(n) is computed as
F(n) = F(n - 1). n for n > 0
The number of multiplication M(n) is computed as
M(n) = M(n - 1) + i for n > 0
Recurrence Relation
• The recurrence relations play an important role in analysis
of an algorithm.
M(n) = M(n - 1) + 1 for n > 0
M(0) = 0
Solving Recurrence equation by backward substitutions
M(n) = M(n - 1) + 1
Substitute M(n - 1) = M(n - 2) + 1
Now M(n) becomes
M(n) = [M(n - 2) + 1] + 1
= M(n - 2) + 2
SNow M(n) becomes
M(n) = [M(n - 3) + 1] + 2
= M(n - 3) + 3
From the above, the general formula is obtained.
The general formula is
M(n) = M(n -i) + i
M(n) = M(n - 1) + 1
Substitute n = 0, i = n
M(n) = M(n - n) = n
= M(0) + n
M(n) = n

To find the number of binary digits in binary representation.


Algorithm Bin Tree (n)
// Input - A positive decimal integer n.
// Output - the number of binary digits in n's binary
representation.
If n = 1
return 1
else
return Bin Ree 2] +1
Recurrence Relation
The recurrence relation is
A(n) = A
+1 forn ≥1
Where
A(n) = No of addition
AL31) = Noofadaion made to compute AL2])
The recursive call end when n = 1 and no addition is made
Backward Substitution
A(2k) = A(2k-1) + 1
Substitute A(2k) = A(2k-2) + 1
A(2k) = [A(2k-2) + 1] = A (2k-2) + 2
Substitute A (2k-2) = A (2k-3) + 1
A(2k) = [A (2k-3) + 1] + 2
= A (2k-3) + 3
......
= A (2k-i) + i
:
= A (2k-k) + k
A (2k) = A(1) + k = k•
n = 2k, hence k = 10g2 n.
A(n) = log2 n € 0 (log n)
7 (a) Explain the Brute force method for closest pair problem
Convex Hull problem
Procedure
Find the closest pair among n points in k dimensional space.
Given a set S = (pl, p2,, pny of n points in the plane find the
two
points of S whose distance is the smallest.
Compute distance between each pair of points and identify
the pair resulting in the shortest distance.
Algorithm
BruteForceClosestPair (P)
//Finds distance between two closest points in the plane by
brute force
/Input: A list P of n (n ≥ 2) points pl(xl, y1), ... , pn(xn, yn)
//Output: The distance between the closest pair of points
D = 00
for i = 1 ton - 1 do
for j= i + 1 to n do
d =min(d, sqrtxi - xj )2 + (vi - yj )2)) //sqrt is square root
return d
Example
* A regional postal service manager might need a solution to
the closest-pair problem to find candidate post-office
locations to be closed.
* One of the important applications of the closest-pair
problem is cluster analysis in statistics. Based on n data
points, hierarchical cluster analysis seeks to organize them in
a hierarchy of clusters based on some similarity metric.
Time complexity of this algorithm is ©(n').

CONVEX HULL PROBLEM


Definition
* Find the convex hull for a given set of points in the plane or
a higher dimensional space.
* A set of points (finite or infinite) in the plane is called
convex if for any two points p and q in the set, the entire line
segment with the endpoints at p and a belongs to the set.
Delete
Backspace
H
Z.
7
Hor
Enter
4
+
hift
1
End
Properties
* The convex hull of a setS of points is the smallest convex
set containing
S. The convex hull of a finite set of points P is the smallest
convex region containing P.
* If S is convex, its convex hull is obviously S itself. If S is a set
of two points, its convex hull is the line segment connecting
these points. If S is a set of three points not on the same line,
its convex hull is the triangle with the vertices at the three
points given; if the three points do lie on the same line, the
convex hull is the line segment with its endpoints at the two
points that are farthest apart
Procedure for Convex hull problem
* The convex-hull problem is the problem of constructing the
convex hull for a given set S of n points.
* To solve it, we need to find the points that will serve as the
vertices of the polygon
* By definition, an extreme point of a conver set is a point of
this set that is not a middle point of any line segment with
endpoints in the set.
* For example, the extreme points of a triangle are its three
vertices, the extreme points of a circle are all the points of its
circumference, and the extreme points of the convex hull of
the set of eight points are Pi Ps, P6, Pr, and P3.

(b) Explain Exhaustive Search and do the same for travellin,


salesman problem and Assignment problem. 110%

TRAVELLING SALESMAN PROBLEM


Concept
* This problem used to find the shortest tour through a given
set of n cites
that visits each city exactly once before returning to the city
where it started.
The problem can be modeled by a weighted graph, with the
graph's vertices representing the cities and the edge weights
specifying the
distances.
Procedure to solve the problem
The problem can be solved by finding the shortest
Hamiltonian circuit
of the graph.
*. Hamiltonian circuit can also be defined as a sequence of n+
1 adjacent vertices Vio, Vis • ••, Vin -1'
& The first vertex of the sequence is the same as the last one
and all the
othern - 1 vertices are distinct
* Thus, we can get all the tours by generating all the
permutations of n - 1 intermediate cities,
* To compute the tour lengths, and find the shortest among
them. Applications
• Convex hulls provide convenient approximations of object
shapes and data sets given.
• In computer animation, replacing objects by their convex
hulls speeds up collision detection.
* To path plan for Mars mission rovers.
• Convex hulls are used in computing accessibility maps
produced from satellite images by Geographic Information
Systems.
* They are also used for detecting outliers by some statistical
techniques.
* An efficient algorithm for computing a diameter of a set of
points, which is the largest distance between two of the
points,
• Finally, convex hulls are important for solving many
optimization problems.
Analysis
Time complexity of Convex hull is O(n').
8.(a) Create
i.) Huffman tree and
ii.)Huffman code for the following string:Erie eyes seen near
lake
PART-C (1x14=14 Marks)
9.(a) Write a pseudo code for Merge sort using divide and
conquer algorithm, set up and solve a recurrence relation for
the number of key comparision made by above pseudo code
MERGE SORT
Concept
Given a sequence of n elements split into 2 sets all.....a 2),
Each set is individually sorted and the resulting sorted
sequence are merged to
produce a single sorted sequence of n elements.
2.6.1. PROCEDURE FOR MERGE SORT
* The first step of the merge sort is divided the list into 2
equal sub lists.
• If the list has even length, split the list into 2 equal sub lists.
* If the list has odd length, divide the list into 2 by making the
first sub list one entry greater than the second sub list.
* Split both the sub list into 2 and go on split until each of the
sub lists are size of one.
* Finally, start merging the individual sub lists to obtain a
sorted list.
ALGORITHM FOR MERGE SORT
2.19
Two pointers are initialized to point to the first elements of
the array
being merged.
The elements are compared and the smaller of both is added
to a new
array.
* The index of the relevant array is incremented.
The above steps are continued until one of the 2 given arrays
is
exhausted.
Then the remaining elements of the other array are copied to
the end of
the new array.
Procedure for Merge Sort
* Algorithm merge sort (A [O...n - 1])
// Sorts array A [O...n - 1]) by recursive procedure.
// Input: An array A [O...n - 1]) of elements.
// Output: Array A [O...n - 1]sorted in non decreasing order.
If (n < 1)
return;
else
Copy A [0 (3)-1]108[°(2)-1]
Сору А [(2) п - 1] го с 0... *) - 1]
ub list
sts are
Merge sort C 0... 2) - 1
Merge (B, C, A)

Merging of 2 sorted array using merge algorithm.


Algorithm merge (B [O...P-1], C [0...9 - 11, A [O...P + q - 1]).
// Merges 2 sorted array into one array.
// Input arrays B [O...P - 1] and C [O...g - 1] both sorted.
Output sorted array [O...P + 9 - 1] of the elements of B and C.
{ i = 0;j = 0; k= 0;
while i < p and j < q do if (B [i] ≤ CU])
{ A [k] = B [];
i = i + 1;3
else
{ A [k] = C[/];
j=j+ 1;
k = k+1
if (i = = P) copy C /...9 - 1] to A [k...P + q - 1]
else copy B [i...P - 1] to A [k...P + q - 1]
2.6.3. EXAMPLES FOR MERGE SORT
Sort the following elements using merge sort 8, 3, 2, 9, 7, 1,
5, 4.
Complexity of an algorithm measured in terms of space and
time.
Space Complexity
1. Space for merge
Each and every recursive call require stack space for the
following elements.
Start, mid, mid + 1, finish
2. Space for merge sort
Space for array ie A, B, & C = 3 n locations.
Space for control variables ie i, j, k = 3 locations.
Time Complexity
The recurrence relation for the number of key comparison
C(n) is
C(n) = 2C
n + C merge (n) > 1 & n(1) = 0
Assume n is power of 2.
C merge (n) -number of key comparison performed during
the merge stage.
* In the merging of 2 sorted array after one comparison is
made the total number of elements in the array still to be
processed and sorted is reduced by one.
% Hence in the worst case, neither of the 2 sorted arrays
becomes empty.
for the worst case
C merge (n) = n - 1
* The merge sort algorithm passes over the entire list and
require almost log n passes and merge n elements in each
pass.
:. total number of comparison required by the merge sort is
0 (n log2n)
2.6.5. MERITS AND DEMERITS OF MERGE SORT
Merits
* It requires less running time
* Used in data processing
* It is used in tape sorting
Demerits
*The algorithm requires linear amount of extra storage
* It requires an additional array with n elements.
* After Merging, the resulting algorithm is quite complicated
and also has a significantly large multiplicative constant.

9(b)write a pseudo code for quick sort using divide and


conquer algorithm, set up and solve a recurrence relation for
the number of key comparision made by above pseudo code
QUICK SORT ALGORTAM
* Quick sort algoritm is used to divide the array into sub
arrays.
% It is recursive algorithm.
Algorithm Quick Sort (A [I ...r])
{// Sorts a sub array by quick sort
// Input: A [...r]
I and r denotes left and right indices.
// Output: The sub array A [I...r] sorted in non decreasing
order.
If (l-r)
{ q= Partition (A [/ ...r]);
Quick sort (A [l...r])
Quick sort (A [g + l...r])
2.27
* Find the position for pivot element using partition
algorithm.
Algorithm Partition (A [I...r])
/ Partitions a sub array by using its first element as a pivot.
// Input A sub array A [...r], / and r indicates left and right
indices.
// Output: A partition of A [l...r] ie return the position of
partition.
I consider first element as pivot.
P=A [I; // P is assigned with first element
QUICK SORT ALGORTAM
* Quick sort algoritm is used to divide the array into sub
arrays.
% It is recursive algorithm.
Algorithm Quick Sort (A [I ...r])
{// Sorts a sub array by quick sort
// Input: A [...r]
I and r denotes left and right indices.
// Output: The sub array A [I...r] sorted in non decreasing
order.
If (l-r)
{ q= Partition (A [/ ...r]);
Quick sort (A [l...r])
Quick sort (A [g + l...r])
2.27
* Find the position for pivot element using partition
algorithm.
Algorithm Partition (A [I...r])
/ Partitions a sub array by using its first element as a pivot.
// Input A sub array A [...r], / and r indicates left and right
indices.
// Output: A partition of A [l...r] ie return the position of
partition.
I consider first element as pivot.
P=A [I; // P is assigned with first element
Time Complexity
Comparisons
2.33
The number of key comparison is "n + I' if the scanning index
i and j
crosses over.
> The number of key comparison is n' if the scanning indices i
and j are coincide.
Best Case Analysis
• tal thesplis happen in the midale of the coreponding sub
arays.
*:. The recurrence relation becomes
C best (n) = 2 (best 2)) +n for n>1
C best (1) = 0
* According to the master theorem
C best (n) = n 10g2 n
Worst Case Analysis
* All the splits will be skewed to the extreme.
* One of the 2 sub arrays will be empty while the size of the
other will be just one less than the size of a sub arrays being
partitioned.
:. total no of comparison will be equal to
C worst (n) = (n + 1) +n+ ...+ 3
= (n+ 1) (n +2) _ 3
C Worst (n) = 0 (n2)
Average Case Analysis
Average number of key comparisons.
* Partition split can be happen in each position q (0 ≤ 9 ≤ n -
1) with the same probability
n
Cavg (n) =
Design and Analysis of Algorith
[(n + 1) + Cavg (q) + C avg (n - 1 - 9)]
forn > 1
Brute Force and Divide
To search a locate the
C avg (0) = 0
C avg (1) = 0
Cavg (n) ~ 2n1•n~ 1.38 n 10g2 n
Choosing Pivot Element
Selection of proper pivot, improve the efficiency of an
algorithm.
* Median of three partitioning method uses pivot as the
median of let most right most and middle element of the
array.
BENEFITS OF QUICK SORT
Sorting time is very less when comparing with all other sorts.
* Idea of partitioning can be useful in many applications.

You might also like