Unit-1 Notes
Unit-1 Notes
Unit – I
INTRODUCTION
Notion Of An Algorithm – Fundamentals Of Algorithmic Problem Solving – Important Problem
Types – Fundamentals Of The Analysis Of Algorithm Efficiency – Analysis Framework – Asymptotic
Notations And Its Properties – Mathematical Analysis For Recursive And Non-Recursive
Algorithms.
PART – A
NOTION OF AN ALGORITHM
Algorithm
Program
A program is the expression of an algorithm in a programming language.
Program Proving
Given a program and a formal specification, use formal proof techniques
(e.g. induction) to prove that the program behaviour fits the specification
Program Verification
Testing to determine whether a program works as specified.
Notion Of An Algorithm
Algorithm Program
1. Algorithm is finite. 1. Program need to be finite.
10. Design an algorithm to compute the area and circumference of a circle. (C)
[Nov/Dec 2016]
11.What are the ways to compute the gcd of two given numbers? (R)
Calculating Greatest Common Divisor
Problem Statement
The Greatest common Divisor (GCD) of two non-zero numbers a and b is basically the
largest integer that divides both a and b evenly i.e., with a remainder of zero.
GCD· - 3 methods
1. Euclid‟s algorithm
2. Consecutive integer checking algorithm
3. Finding GCD using repetitive f a c t o r s
12.Write the Consecutive Integer Checking algorithm to calculate the gcd of two
numbers. (AP)
13. Give the Euclid’s algorithm for computing gcd(m,n). (U) [May/June 2016]
Euclid’s algorithm
Euclid's algorithm is based on applying related equality gcd (m, n) gcd (n, m mod n)
ALGORITHM Euclid(m, n)
//Computes gcd(m, n) by Euclid’s algorithm
//Input: Two nonnegative, not-both-zero integers m and n
//Output: Greatest common divisor of m and n
while n = 0 do
r ←m mod n
m ←n
n ←r
return m
14.What are six step processes in algorithmic problem solving?[Dec 2009] (U)
Algorithmic Problem Solving
15.Draw the flow diagram of algorithm design and analysis process. (R)
Input
Output
Definiteness
Finiteness
Efficiency
Un ambiguity
28.Write an algorithm to find the number of binary digits in the binary representation of
a positive decimal integer. [May 2015] (C)
Algorithm BinRec(n)
//Input: A positive decimal integer n
//Output: The number of binary digits in n's binary representation
if n=l
return 1
else
return BinRec([n/2])+ 1
29.Explain the various types of problems that can be solved using algorithm. (R)
Types Of Problems
1. Sorting
2. Searching
3. String Processing
4. Graph problems
5. Combinatorial Problems
6. Geometric problems
7. Numerical problems.
30.What is sorting?(R)
Sorting
31.What are the properties used for analysing various sorting algorithms? (U)
Properties of Sorting Algorithms
Stable
A sorting algorithm is called stable, if it preserves the relative order of any two equal
elements in its input.
In other words, if an input list contain two equal elements in positions i and j, where
i<j, then in the sorted list they have to be in position i' and j' respectively, such
that i' <j'
In-place
An algorithm is said to be in-place if it does not require extra memory, except, possibly
for a few memory units.
Geometric algorithms deal with geometric objects such as points,lines and polygons.
The procedure for solving a variety of .geometric problems includes the problems
of constructing simple geometric shapes such as triangles, circles.
The two classic problems of computational geometry ate:
Closest pair problem
Given n points in the plane, find the closest pair among them.
Convex hull problem
Find the smallest-convex polygon that would include all the points of a
given set.
34.What do you mean by linear search? [Nov 2011, May 2012] (R)
Sequential Search or Linear Search
Problem Statement
To search for a given item using some search key K in a list of „n' elements by checking
successive elements of the list until a match with the search key is found or the list is
exhausted.
35.What are the factors used to measure the performance of an algorithm? (A)
Factors used to measure the performance of an algorithm
Space efficiency, also called Space complexity, refers to the amount of memory units
required by the algorithm to run in addition to the space needed for its input and output.
Factors for computing the space complexity - Constant and Instance characteristics.
Space requirement S(P) can be given as
S(p) = C+
Where C is a constant i.e. fixed part and it denotes the space of inputs and outputs
i=0 1
i++ n times
Sum=sum+a[i] n times
Total 3n+2
Measuring the performance of an algorithm in relation with the input size n is called order of
growth. For example, the order of growth for varying input size of n is as given below.
N log n n log n n2 2n
1 0 0 1 2
2 1 2 4 4
4 2 8 16 16
Page | 12
Unit-I/Introduction
Polynomials of degree m n m .That means maximum degree is considered from the
polynomial.
1 log n n n 2 2 n .
2
43.Compare the orders of growth of n(n-1)/2 and n . [May/June 2016]
2
Orders of growth of n(n-1)/2 and n
2
n(n-1)/2 = n! n
1!=1 12 = 1
2!=2x1=2 22 =2
3!=3x2x1=6 32=9
4!=4x3x2x1=24 42=16
2
Therefore N(n-1)/2 has higher order of growth than n
Constant
Logarithmic
Linear
Quadratic
Cubic
Exponential
Factorial
Time space tradeoff is basically a situation where either space efficiency (memory
utilization) can be achieved at the cost of time or time efficiency (performance
efficiency) can be achieved at the cost of memory.
Consider the programs like compilers in which symbol table is used to handle the
variables and constants. Now if entire symbol table is stored in the program then the time
required for searching or storing the variable in the symbol table will be reduced but
memory requirement will be more.
Basic Operation
The main objective is to identify the most important operation of the algorithm, called
the
Basic Operation - the operation contributing the most to the total running time
T(n) ~ C(n)
Where
T(n) - running time
C(n) - no. of times this operation is executed.
Cop - execution time of algorithms basic operation.
The runtime of an algorithm cannot be measured in standard unit of time because in multiuser
system running time depends on many factors such as:-
System load
Number of other program running
Instruction set used
Speed of underlying hardware
U20IT303/Design and Analysis of Algorithm Page | 14
Unit-I/Introduction
Worst case time complexity is a time complexity when algorithm runs for a longest time. We
can denote the worst case complexity as,
Cworst = n
The algorithm guarantees that for any instance of input which is of size n, the running time will
not exceed Cworst (n). Hence the worst case time complexity gives important information about
the efficiency of algorithm.
Average complexity gives information about the behavior of an algorithm on specific random
input.
Example, for sequential search and P be a probability of getting successful search. n is the total
number of elements in the list.
Cavg (n) = Probability of successful search + Probability of unsuccessful search
Best case time complexity is a time complexity when an algorithm runs for short time. In the
searching algorithm the element key is searched from the list of n elements. We can denote the
best case time complexity as
Cbest = 1
The algorithm guarantees that for any instance of input which is of size n, the running time will
not exceed Cbest (n).
51. Analyse the time efficiency of linear search? Nov/Dec 2011. (A)
Analysis of Linear Search
Worst case : if we get the element at the first place then it is a best case time complexity
because in this case algorithm takes minimum amount of time to run to its completion.
Average case : if the element is present at the end of the list or it is not all present in the list,
then it is called worst case time complexity because in this case algorithm takes maximum
amount of time to run to its completion
Amortized analysis finds the average running time per operation over a worst
case sequence of operations
It applies not to a single run of an algorithm but rather to a sequence of operations
performed on the same data structure.
It turns out that in some situations a single operation can be expensive, but the total time
for an entire sequence of n such operations is always significantly better than the worst-
case efficiency of that single operation multiplied by n.
So we can “amortize” the high cost of such a worst-case occurrence over the entire
sequence in a manner similar to the way a business would
53.Using the step count method analyze the time complexity when 2m*n matrices
are added. [May 2011] (E)
F n c g n
If there are two functions f1 n and f 2 n such that f1 n g1 n and f 2 n g 2 n
then f1 n + f 2 n =max g1 n, g 2 n.
If there are two functions f1 n and f 2 n such that f1 n g1 n and f 2 n g 2 n
then f1 n * f 2 n = g1 n * g 2 n .
If there exists a function f1 such that f1 f 2 * c where c is a constant then, f1 and f 2 are
equivalent. That means
If f n g n and f1 f 2 f1 f 2 . g n hn then f n hn.
A function F(n) is said to be in (g(n)) if F(n) is bounded below by some positive constant
multiple of g(n) such that
The theta notation is denoted by „ ‟. By this method the running time is between upper bound
and lower bound. Let F(n) and g(n) be two non-negative functions. There are two positive
constants namely c1 and c2 such that,
Polynomials of degree m n m .That means maximum degree is considered from the
polynomial.
1 log n n n 2 2 n .
Exponential functions an have different orders of growth for different values of a.
Recurrence Equation
Here equation 1 is called recurrence relation and equation 2 is called initial condition. The
recurrence equation can have infinite number of sequences. The general solution to the
recursive function specifies some formula.
Substitution method
Forward substitution (This Process continued until some formula is guessed)
Backward substitution (Values are substituted recursively)
Master method
Tree method (recursive function)
The substitution method guess for the solution is made. There are two types of substitution:
Forward substitution
Backward substitution
Forward substitution method: This method makes use of an initial condition in the initial term
and value for the next term is generated. This process is continued until some formula is
guessed.
Backward substitution method : Values are substituted recursively in order to derive some
formula.
Solution
M (n) = M (n − 1) + 2
= [M (n − 2) + 2] + 2 = M (n − 2) + 2 + 2
= [M (n − 3) + 2] +2+2 = M (n − 3) +2+2 + 2
= ...
= M (n − i) + 2i
.
M (n) = 2(n − 1)
64.Solve the following recurrence equation S n S n 1 4n for n 0 and S 0 1 using
backward substitution method. (AP)
Solution
S (n) = S (n − 1) + 4n
= ...
= ...
65.Solve the following recurrence equation Cn Cn / 2 Cn / 2 1, for n 1, C1 0
(solve for n=2k). (AP)
Solution
C (2k) = 2C (2k-1) + 1
= ...
= ...
66.Solve the following recurrence equation An 2 An 1 1 and A0 0 using backward
substitution method. (AP)
Solution
A (n) = 2A (n − 1) + 1
= 2[2A (n − 2) + 1] + 1 = 22 A (n − 2) + 2+ 1
= 22[2A (n − 3) + 1] + 2 + 1 = 23 A (n − 3) + 22 + 2+ 1
= ...
= ...
A (n) =2n − 1.
67.Solve the following recurrence equation Qn Qn 1 2n 1 for n > 1, Q1 1. (AP)
Solution
Computing the first few terms of the sequence yields the following:
Q(2) = Q(1) + 2 · 2 − 1 = 1 + 2 · 2 −1 = 4;
Q(3) = Q(2) + 2 · 3 − 1 = 4 + 2 · 3 −1 = 9;
Thus, it appears that Q(n) = n2. We‟ll check this hypothesis by substituting this formula into the
recurrence equation and the initial condition. The left hand side yields Q(n) = n2. The right hand
side yields
69.What is the general plan for analyzing efficiency of non recursive algorithm? (U)
General plan for analyzing efficiency of non recursive algorithm
70.What is the general plan for analyzing efficiency of recursive algorithm? (U)
General plan for analyzing efficiency of recursive algorithm
Then the master theorem can be stated for efficiency analysis as:-
If F n is n d where d 0 in the recurrence relation then,
1. T n n d if a b d
3. T n n
logb a
if a b d
Solution:
73.Solve the following recurrence relation Cn Cn 1 1, C0 1 using substitution
method. (AP)
Solution:
C (n) = C (n − 1) + 1
= [C (n − 2) + 1] + 1
= C (n − 2) + 2
= ...
= C (n − i) + i
= ...
= C (0) + n
C (n) = 1+n
PART – B
NOTION OF AN ALGORITHM
1. Explain the notion of an algorithm with diagram. [16M] [May 2014] (U)
Notion Of An Algorithm
Algorithm
Structure of an Algorithm
Algorithm heading
Name Of Algorithm
Problem Description
Input & Output
Algorithm Body
Logical Body of the Algorithm
Programming Constructs
1. Heading
Algorithm is a product consisting of heading and body. The heading consists of
keyword algorithm and name of the algorithm and parameter list. The syntax is
Algorithm name (p1, p2, pn)
Then in the heading section we should write following things:
Problem Description
Input
Output
2. Body Of An Algorithm
Then body of an algorithm is written, in which various programming constructs like if,
for, while or some assignment statement may be written.
3. The compound statements should be enclosed within {and} brackets.
4. Single line comments are written using // as beginning of comment.
5. The identifier should begin by latter and not by digit. An identifier can be a
combination of alphanumeric string.
6. Data Types
It is not necessary to write data types explicitly for identifiers. It will be
represented by the context itself.
Basic data types integer, float, and char, Boolean
Compound data type structure or record
The pointer type is also used to point memory locations.
7. Operators
Boolean operators true or false
Logical operators AND, OR, NOT
Relational operators <, <=, >, >=, =, !=.
Assignment Operator (=)
8. Array Indices
Stored with in square brackets []. The index of array usually starts at zero.
The multidimensional arrays can also be used in algorithm.
9. Inputting And Outputting read and write.
For example:
write ("this message will be displayed on console ");
read (Val);
10. Conditional Statements if -then - else
if (condition)
then statement
else
statement
Note:The statements in an algorithm executes in sequential order i.e. in the same order as
they appear - one after the other
Implementation of algorithms
An algorithm describes what the program is going to perform. It states some of the
actions to be executed and the order in which these actions are to be executed.
The various steps in developing algorithm are,
1. Finding a method for solving a problem.
2. The next step is to validate the algorithm.
3. Finally, implement the algorithm in terms of programming language.
Order of an algorithm
The order of an algorithm is a standard notation of an algorithm that has been developed to
represent function that bound the computing time for algorithms. It is an order notation. It is
usually referred as O-notation.
Example
Problem size = 'n'
Algorithm = 'a' for problem size n
The document mechanism execution = Cn2 times
where C - constant
Program
3. Write an algorithm to check whether given number is even or odd. [6M] (C)
Method-I
Euclid's algorithm to compute Greatest. Common Divisor (GCD) of two non-
negative integers.
Until m=0,n=0
Where m mod n is the remainder of the division of m by n
ALGORITHM Euclid(m, n)
//Computes gcd(m, n) by Euclid’s algorithm
//Input: Two nonnegative, not-both-zero integers m and n
//Output: Greatest common divisor of m and n
while n = 0 do
r ←m mod n
m ←n
n ←r
return m
Method II
Consecutive Integer Checking Algorithm
In this method while finding the GCD of a and b we first of all find the minimum value
of them.
Suppose if value of b is minimum then we start checking the divisibility by each
integer which is lesser than or equal to b.
Example:
a = 15 and b =10 then t= min( 15,10)
since 10 is minimum we will set value of t = 10 initially.
Method III
Finding GCD using repetitive factors
The third procedure for finding the greatest common divisor is middle school procedure
The next principal decision is to choose between solving the problem exactly and solving the
problem approximately.
In Object Oriented Programming, the data structure is important for both design and
analysis of algorithms.
The variability in algorithm is due to the data structure in which the data of the program are
stored such as
1. How the data are arranged in relation to each other?
2. Which data are kept in memory?
3. Which data are kept in files and how the files are arranged?
4. Which data are calculated when needed?
Once an algorithm has been specified, then its correctness must be proved.
An algorithm must yield a required result for every legitimate input in a finite
amount of time.
Mathematical Induction is a common technique used to prove the correctness of
the algorithm. In mathematical induction, an algorithm‟s iterations provide a natural
sequence of steps needed for proofs. If the algorithm is found incorrect, need to
redesign it or reconsider other decisions.
8. Analysing an algorithm
Dependency Factors
Simplicity Of An Algorithm
Generality
9. Coding an Algorithm
1. Sorting
Problem Description:
Sorting .is the operation of arranging the records of a table according to the key value of the
each record.
Example : Sort student records in alphabetical order of names or by student number or by
student grade-point average(Key)
Stable
A sorting algorithm is called stable, if it preserves the relative order of any two equal
elements in its input.
In other words, if an input list contain two equal elements in positions i and j, where
i<j, then in the sorted list they have to be in position i' and j' respectively, such
that i' <j'
In-place
An algorithm is said to be in-place if it does not require extra memory, except, possibly
for a few memory units.
Types of Sorting
Internal Sorting methods External Sorting methods
The key principle of internal sorting is The idea behind the external sorting is to
that all the data items to be sorted are move data from secondary storage to mail
retained in the main memory and random memory in large blocks for ordering the
access memory. data.
2. Searching
Problem Statement : Searching is an activity by which we can find out the desired element
from the list. The element which is to be searched is called search key.
One of the important applications of array is searching
Searching Algorithm:
1. Sequential Search
2. Fibonacci search
3. String Processing
4. Graph Problems
Graph Problems
1. Graph Traversal Algorithms,
2. Shortest Path Algorithm
3. Topological Sorting.
4. Travelling Salesman Problem
5. Graph Colouring Problems
5. Combinatorial Problems
Problem Statement: A combinatorial object such as a permutation a combination or a subset
that satisfies certain constraints and has some desired property such as
maximizes a value or minimizes a cost .
6. Geometric Problems
Geometric algorithms deal with geometric objects such as points,lines and polygons.
The procedure for solving a variety of .geometric problems includes the problems
of constructing simple geometric shapes such as triangles, circles.
The two classic problems of computational geometry ate:
Closest pair problem
Given n points in the plane, find the closest pair among them.
Convex hull problem
Find the smallest-convex polygon that would include all the points of a
given set.
The geometric problems are solved mainly in applications to computer
graphics or in robotics
7. Numerical problems
Analysis Framework
Overview
1. Space complexity
2. Time complexity
3. Measuring an Input's size
4. Measuring Running Time
5. Orders of Growth
2. Space complexity
S(p) = C+
Where C is a constant i.e. fixed part and it denotes the space of inputs and outputs.
3. Time complexity
Basic Operation
Example
Most sorting algorithms work by comparing the elements (keys) of a list being .sorted
with each other. For. such algorithms the basic operation is a Key Comparison.
T(n) ~ C(n)
Where
T(n) - running time
C(n) - no. of times this operation is executed.
Cop - execution time of algorithms basic operation.
4. Orders of Growth
Measuring the performance of an algorithm in relation with the input size „n‟ is called
order of growth.
N log n n log n n2 2n
1 0 0 1 2
2 1 2 4 4
4 2 8 16 16
Constant
Logarithmic
Linear
Quadratic
Cubic
Exponential
Factorial
Properties Of Order Of Growth
If F1 (n) is order of g1 (n) and F2 (n) is order of g2 (n), then
F1 (n) +F2 (n) max g1 n, g 2 n .
Polynomials of degree m n m .That means maximum degree is considered from the
polynomial.
1 log n n n 2 2 n .
Time Space Tradeoff
Time space tradeoff is basically a situation where either space efficiency (memory utilization)
can be achieved at the cost of time or time efficiency (performance efficiency) can be achieved
at the cost of memory.
Example:
Consider the programs like compilers in which symbol table is used to handle the variables and
constants. Now if entire symbol table is stored in the program then the time required for
searching or storing the variable in the symbol table will be reduced but memory requirement
will be more.
11. Explain how analysis of linear search is done with a suitable illustration.
[Nov2011-10M] (E)
Or
Write an algorithm for linear search and analyse the algorithm for its time
complexity. [May 2011 - 8M] (A)
Or
Analyse the best case, average and worst case analysis for linear search.•
[Dec 2012-8M] (A)
Or
Use the most appropriate notation to indicate the time efficiency class of sequential
search algorithm in the worst case, best case and the average case. [8M] [May 2016 ]
[Nov-2016] (E)
The running time depends not only on an input size but also on the specifics of a particular
input.
Example: Sequential Search or Linear Search
Design and Analysis of Algorithm Page | 42
Unit-I/Introduction
Problem Statement
To search for a given item using some search key K in a list of „n' elements by checking
successive elements of the list until a match with the search key is found or the list is
exhausted.
The worst case efficiency of an algorithm is its efficiency for the worst case input of size n,
which is an input (or inputs) of size n. For which the algorithm runs the longest among all
possible of that size.
The best case efficiency of an algorithm is its efficiency for the best case input of size
n, which is an input (or inputs) of size n for which the algorithm runs the fastest among
all possible inputs of that size.
Determination of best case efficiency of an algorithm
First, determine the kind of inputs of size n.
Then ascertain the value of C(n) on these inputs.
For sequential search, the best case inputs will be lists of size 'n' with their first elements
equal to a search key.
Amortized Efficiency.
12. Explain the Asymptotic Notations and its properties in detail? [May 2011-
8M](R)
(or)
Discuss in detail all the asymptotic notations with example. [May 2012 -16M] (R)
(or)
Distinguish between Big oh, Theta and Omega Notations.[Dec 2012-8M] (R)
(or)
Give the definition and Graphical representation of O-notations. [8M][May-
2016](R)
Asymptotic Notations
1. Big Oh Notation
F n c g n
n=1
F n 2n 2 21 2
g n 1
F n g n
Page | 45
Unit-I/Introduction
If n = 2 then,
F n 2n 2 22 2 6
g n 2 4
2
g n 4
F n g n
If n = 3 then
F n 2n 2 23 2 8
g n 3 9
2
Hence we can conclude that for n > 2, we obtain F n g n . Thus always upper bound of
existing time is obtained by big oh notation.
2. Omega Notation
A function F(n) is said to be in (g(n)) if F(n) is bounded below by some positive constant
multiple of g(n) such that
F n c g n for all n n0 .
It is denoted as F n g n .
Example:
If n = 0
F n 20 5 5
2
Page | 46
Unit-I/Introduction
But if n = 1
F n 21 5 7
2
If n = 3 then
F n 23 5 23
2
It can be represented as
2n 2 5 n
3. Theta Notation
The theta notation is denoted by „ ‟. By this method the running time is between upper bound
and lower bound. Let F(n) and g(n) be two non-negative functions. There are two positive
constants namely c1 and c2 such that,
Example:
If n = 1 then
F n 21 8 10
g n 7(1) 7
5n 2n 8 7n For n 2
Page | 47
Unit-I/Introduction
13. State the general plan for analysing the time efficiency of non-recursive
algorithms and explain with an example.[16M] [Nov-2016] (U)
or
Define recurrence equation and explain how solving recurrence equations are
done. [Nov 2011 - 6M](U)
Recurrence Relation
a. Substitution method
b. Masters method
Substitution Method
In substitution method a guess for solution is made. There are two types of
substitution:
Forward substitution
Backward substitution
Forward substitution:
In this method makes use of an initial condition in the initial term and value for the
next term is generated. This process is continued until some formula is guessed.
Example:
Let,
Page | 48
Unit-I/Introduction
If n = 1 then
T 1 T 0 1 0 1
If n = 2 then
T 2 T 1 2 1 2
If n = 3 then
T 3 T 2 3 3 3
nn 1 n 2 n
T n
2 2 2
T n n 2
Backward substitution:
In this method backward values are substituted recursively in order to derive some
formula.
T n 1 T n 1 1 n 1 ………………….. (2)
Page | 49
Unit-I/Introduction
Let
T n 2 T n 2 1 n 2 …………... (4)
T n T n 3 n 2 n 1 n
………….
T n T n k n k 1 n k 2 n..... n
If k = n then
T n 0 1 2 ....n
nn 1 n 2 n
T n
2 2 2
T n n 2
Masters Method:
Now f n is n. n1 .hence d = 1
a = 4 and b = 2 and
a b d i.e. 4 > 2
1
T n n logb a
T n n log2 4
T n n 2
log 2 4 2
PART – C
ASYMPTOTIC NOTATIONS AND ITS PROPERTIES
1. Give the Algorithm to check whether all the elements in a given array of n
elements are distinct. Find the worst case complexity of the
same.[8M][May2016] (C)
n
nn 1
i
i 1 2
n
n 2n 1 1 n 1 1 n
= n 1n 1 i 1
n2
2
1 n 2 0 1 n 1
i 0
2. Derive the worst case analysis of Merge sort with suitable illustration. [8M]
[May/June 2015] (AP)
Merge Sort
Merge sort is a perfect example of a successful application of the divide and conquer technique.
It sorts a given array A[0...n-l] by dividing it into two halves
Sorting each of them recursively, and then merging the two smaller sorted arrays into a single
sorted one.
The merging of two sorted arrays can be done as follows. Two pointers (array indices) are
initialized to point to the first elements of the arrays being merged. The elements pointed to are
compared, and the smaller of them is added to a new array being constructed; after that, the
index of the smaller element is incremented to point to its immediate successor in the array it
was copied from. This operation is repeated until one of the two given arrays is exhausted, and
then the remaining elements of the other array are copied to the end of the new array.
(3)
Complexity
Simplicity that n is a power of 2, the recurrence relation for the number of key comparisons
C(n) is
C(n) = 2C(n/2) + Cmerge(n) for n > 1, C(1) = 0.
Page | 53
Unit-I/Introduction
In the worst case, neither of the two arrays becomes empty before the other one contains just
one element (e.g., smaller elements may come from the alternating arrays). Therefore, for
the worst case, Cmerge(n) = n − 1, and the recurrence
Cworst(n) = 2Cworst(n/2) + n − 1 for n > 1, Cworst(1) = 0.
Hence, according to the Master Theorem, Cworst(n) ∈ Θ(n log n) (why?). In fact, it is easy
to find the exact solution to the worst-case recurrence for n = 2k:
Cworst(n) = n log2 n − n + 1.
3. Write the insertion sort algorithm and estimate the running time. [8M]May/June
2015 (AP)
It is a simple Sorting algorithm which sorts the array by shifting elements one by one.
Following are some of the important characteristics of Insertion Sort.
INSERTION_SORT (A)
for j ← 2 to length[a]
do key ← a[j]
{put a[j] into the sorted sequence a[1 . . j − 1]}
i←j−1
while i > 0 and a[i] > key
do a[i +1] ← a[i]
i←i−1
a[i + 1] ← key
The running time of an algorithm for a specific input depends on the number of operations
executed. The greater the number of operations, the longer the running time of an algorithm
Average complexity=Θ(N2)
Page | 54
Unit-I/Introduction
Solution
T n n n n
Step 4
n n
..............n
..............n
N n
Page | 55
Unit-I/Introduction
The depth of the tree is log n. hence we can guess that, total cost= n log n T (1). Hence we get
the overall cost as n log n .
Solution
Cn2
.
.
………………………………………….
n n
Thus size for a node at depth i is
i
. If n = 1 the i =1. Hence n=4i. Hence log 4 n i. thus
4 4
2
n
depth i= (0, 1, 2,……..+ log 4 n 1 ) = log 4 n 1 and cost of each node is C i .
4
Page | 56
Unit-I/Introduction
2
i n
3 C i is overall cost =
3
C n2 . The last level at depth log 4 n has
4 16
3 log4 n
n log4 3 n log4 3 .
(i) Solve the recurrence relation T n T T n .... using the tree
n 2n
6.
3 3
method. [8M] (AP)
Solution
N n
log 3 / 2 n
4. (ii). If T1n f n and T2 n g n then show that
T1n T2 n max f n, g n . [8M] (AP)
Solution
Page | 57
Unit-I/Introduction
Hence
T1 n T2 n max g1 n g 2 n is true.
5. Explain various methods used for solving Fibonacci series and calculate
their efficiencies. [16M] (A)
Fibonacci series
Mathematical Analysis
Solution:
T n 2T n 1 1
Page | 58
Unit-I/Introduction
T n 22T n 2 1 1
T n 42T n 3 1 1 2
T n 2 k T n k 2 k
T n 2 n T n n 2 n where k = n
T n 2 n T 0 2 n
T n 2 n
6. Find the time complexity and space complexity Factorial using recursion and
compare nth Fibonacci number using Iterative statements.[Dec 2012-
8M](A)
Factorial
Step 1: n! = 5!
Step 2: 4!*5
Step 3: 3!*4*5
Step 4: 2!*3*4*5
Step 5: 1!*2*3*4*5
Step 6: 1*1*2*3*4*5
Page | 59
Unit-I/Introduction
Mathematical Analysis
M n M n 1 1
Solution
M n M n 1 1
= M n 2 1 1 M n 2 2
= M n 3 1 1 1 M n 3 3
From the substitution methods we can establish a general formula as:
M n M n i i
Put i=n
M n M 0 n
Hence M n n
Thus the time complexity of factorial function is n .
Solution
n
T n k .T n 2 be a recurrence relation.
k
Page | 60
Unit-I/Introduction
2
n
T n 2T n 2 where T 2T
n n n
2 2 4 2
n n2
= 22.T n 2
4 4
n n2
= 4T n2
4 2
2
n 3n
where T 2T
2
n n n
= 4T
4 2 4 8 4
n n 2 3n 2
= 42.T
8 16 2
n n 2 3n 2
= 8T
8 4 2
n 7n 2
= 8T
8 4
n 2 1 2
k
= 2k T k 1
n
2 2
k
2k 1
= 2 T k Cn 2
n
k
k 1 C Constant
2 2
n
If we put 1 then 2 k n and k log 2 n
2k
= nT 1 Cn 2
= n Cn 2
T n = n 2
a.
2 n 2
T n 8T n [8M]
T n 9T n n 3
[8M]
b. 3
a. 2 n
T n 8T n 2
Solution
Here f n n 2
a 8, b 2
log 2 8 3
f n n logb a
f n n log2 8
= n 3 If we put 1 then n 3 1 n 2 f n
T n = n 3
b. 3 n
T n 9T n 3
(8)
Solution
And log 3 9 2
f n n 2 and we have f n n 3
T n n 3
a.
2 1
T n T n [8M]
T n 9T n n [8M]
b. 3
a. T n T n 2 1
Solution
Here a = 1 and b = 2.
And log 2 1 0 now we will analyze f n 1 .
We assume f n 2 k
f n n logb a log k n
f n 1 n0 1
We get T n n logb a log k 1 n
T n n log2 1 log 01 n
T n log n n0 1
b. T n 9T n 3 n (8)
Solution
Here a = 9, b = 3 and f n n
n logb a n log3 9 n 2
Now f n n
T n f n n logb a n 2
When 1 . That means case 1 is applicable. According to case 1, the time
complexity of such equation is
T n n logb a
T n n 2
Matrix Multiplication
Mathematical Analysis
= [For loop using i] [For loop using j] [For loop using k](1 execution)
n 1 n 1 n 1
M n 1
i 0 j 0 k 0
n 1 n 1
M n n
i 0 j 0
n 1
M n n2
i 0
M n n3
Thus the simplified sum is n3. Thus the time complexity of matrix multiplication
n3 .
11. Find whether all the elements in an array are distinct and analyze the efficiency
using non-recursive algorithm. [16M] (AP)
Mathematical Analysis
n2 n 1
C worst n 1
i 0 j i 1
n 1
n
1 n 1 i 1 1
j i 1
1 n k 1 is the rule.
i k
n2
= n 1 i
i 0
n2 n2
= n 1 i
i 0 i 0
= n 11
n2
n 2n 1 this can be obtained using formula
i 0 2
n
nn 1
i
i 1 2
n 2n 1 1 n 1 1 n
= n 1n 1 i 1
n2
2
1 n 2 0 1 n 1
i 0
=
2 n 2 2n 1 n 2 3n 2
2
=
n 2
n
2
1 2
= n
2
12. Find the element with maximum value in a given array and analyze the
efficiency of an algorithm using non-recursive method. [16M] (AP)
Algorithm Max_Elements(A[0…..n-1])
Max_value A[0]
for i 1 to n-1 do
{
if(A[i]>Max_value) then
Max_value A[i]
}
return Max_value
Mathematical Analysis
n 1
C n 1
i 1
n
C n n 1 n [Using the rule 1 n n ]
i 1
Page 68