Block 1
Block 1
1.0 Introduction
1.1 Objective
1.2 Example of an Algorithm
1.3 Basics Building Blocks of Algorithms
1.3.1 Sequencing Selection and Iteration
1.3.2 Procedure and Recursion
1.4 A Survey of Common Running Time
1.5 Analysis & Complexity of Algorithm
1.6 Types of Problems
1.7 Problem Solving Techniques
1.8 Deterministic and Stochastic Algorithms
1.9 Summary
1.10 Chapter Review Questions
1.11 Further Readings
1.0 INTRODUCTION
In this unit, the basics of the algorithms and its designing process will be
discussed. Section 1.3 will define the algorithm and its uses with suitable
example. An algorithm is designed with five basic building blocks, namely
sequencing, selection, and iteration. A detailed discussion about these building
blocks of an algorithm is presented in Section 1.4.
1
Basics of An Algorithm And
Its Properties
The solution of a problem can be achieved through a number of algorithms. To
check which algorithm is better than the others, a parameter, known as time
complexity, is used. Therefore, time complexity is one of the important
concepts related to algorithm which are discussed in Section 1.5. Section 1.6
deals with the analysis of Algorithms. To compare Algorithms, complexity is
the parameter to be considered. Computing problems are categorized according
to their solving approach. These are discussed in section 1.7. Section 1.8
comprises the solving techniques of various computing problems. In section
1.9 Deterministic and Stochastic Algorithm are discussed. An algorithm is
deterministic if the next output can be predicted/ determined from the input
and the state of the program, whereas stochastic algorithms are random in
nature.
1.1 OBJECTIVES
2
Introduction to Algorithms
5. Finiteness: The transformation of input to output must be achieved in
finite steps, i.e. the algorithm must stop, eventually! Stopping may
mean that it should produce the expected output or a response that no
solution is possible.
The pseudo code for computing GCD (a, b) by Euclid’s method is as follows:
To validate the algorithm, it must produce the desired result within finite
number of steps. The above-mentioned algorithm has two inputs and one
output. The algorithm is also definiteness and written in basic and effective
sentences. The algorithm is also finite as it terminates in finite steps. To
observe the same, let us find the GCD of a = 1071 and b = 462 using Euclid’s
algorithm.
Iteration 1:
3
Basics of An Algorithm And
Its Properties
r = 147
2. If r = 0, the algorithm terminates and b is the GCD. Otherwise, go to
Step 3.
Here, r is not zero, so we will go to Step 3.
3. The integer will get the current value of integer b and the new value of
integer b will be the current value of r.
Here, a=462 and b=147
4. Go back to Step 1.
Iteration 2:
4
Introduction to Algorithms
Algorithm GCD-Euclid (a, b)
begin [start of Algorithm]
{
while b ≠ 0 do
{
r ← a mod b;
a ←b;
b← r;
} [end of while loop]
return (b)
} [end of algorithm]
2. Selection Decision
4. Procedure
5. Recursion
Step3 is also acts as iteration or the looping statements. Based on the while
loop condition, the Step4 to Step8 are executed in repeatedly manner.
6
Introduction to Algorithms
1.3.2 Procedure & Recursion
(i) Procedure
(ii) Recursion
Procedure
Among a number of terms that are used, instead of procedure, are subprogram
and even function. These terms may have shades of differences in their usage
in different programming languages. However, the basic idea behind these
terms is the same, and is explained next.
It may happen that a sequence frequently occurs either in the same algorithm
repeatedly in different parts of the algorithm or may occur in different
algorithms. In such cases, writing repeatedly of the same sequence, is a
wasteful activity. Procedure is a mechanism that provides a method of
checking this wastage. For example we can define GCD(a, b) as a
procedure/function only once and can call it a number of times in a main
function with different values of a and b
In cases of procedures which pass a value to the calling program another basic
construct (in addition to assignment, read and write) viz., return (x) is used,
where x is a variable used for the value to be passed by the procedure.
Recursion
7
Basics of An Algorithm And
Its Properties
in which the factorial of a natural number n is defined:
factorial (1) = 1
For those who are familiar with recursive definitions like the one given above
for factorial, it is easy to understand how the value of (n!) is obtained from the
above definition of factorial of a natural number. However, for those who are
not familiar with recursive definitions, let us compute factorial (4) using the
above definition.
By definition
factorial (4) = 4 * factorial (3).
Again by the definition
factorial (3) = 3 * factorial (2)
Similarly
factorial (2) = 2* factorial (1)
And by definition
factorial (1) = 1
Substituting back values of factorial (1), factorial (2) etc., we get factorial (4) =
4.3.2.1=24, as desired.
In the following procedure factorial (n), let fact be the variable which is used
to pass the value by the procedure factorial to a calling program. The variable
fact is initially assigned value 1, which is the value of factorial (1).
fact: integer;
begin
fact 1
else begin
return (fact)
end;
end;
8
Introduction to Algorithms
Definition: A procedure, which can call itself, is said to be recursive
procedure/algorithm. For successful implementation of the concept of
recursive procedure, the following conditions should be satisfied.
(i) There must be in-built mechanism in the computer system that
supports the calling of a procedure by itself, e.g, there may be in-built
stack operations on a set of stack registers.
(ii) There must be conditions within the definition of a recursive procedure
under which, after finite number of calls, the procedure is terminated.
(iii) The arguments in successive calls should be simpler in the sense that
each succeeding argument takes us towards the conditions mentioned in
(ii).
Recursion is an important construct which will be used extensively to solve
sorting algorithms, searching algorithm, matrix multiplications, etc.
For a given problem, more than one algorithm can be designed. However, one
algorithm may be better than the other. To compare two algorithms for a
problem, running time is generally used which is defined as the time taken by
an algorithm in generating the output. An algorithm is better if it takes less
running time. The “time” here is not necessarily the clock time. However, this
measure should be invariant to any hardware used. Therefore, the running time
of an algorithm can be represented in terms of the number of operations
executed for a given input. More the number of operations, the larger the
running time of an algorithm. So, if we can find the number of operations
required for a given input in an algorithm then we can measure the running
time. This running time of an algorithm for producing the output is also known
as time complexity. Time here is not the clock time
Following are the generalized form of running time for the algorithms:
9
Basics of An Algorithm And
Its Properties
T(n)=1
k
minimum = a[1]
for ί = 2 to n
if a[ί] < minimum
minimum = a[ί]
end
end if
T(n)=kn
k
T(n)=kn
10
Introduction to Algorithms
3. Logarithmic Time(log(n)): If the time complexity of an algorithm is
proportional to the logarithm of the input size, then it is known as
logarithmic time complexity and depicted as O(log n)time. For example
running time of binary search algorithm is O(log n).O(n log n) is a very
common running time for many algorithms which are solved through
divide and conquer technique such as Merge sort ,Quick sort
algorithms, etc., The common operations among all these problems are
in splitting of the array in equal sized sub-arrays and then solve it
recursively.
T(n)=log(n)
T(n)=log(n)
Quadratic Time: (T(n)= O(n)2)- It occurs when the algorithm is having a pair
of nested loops. The outer loop iterates O(n) time and for each iteration the
inner loop takes O(n) time so we get O(n2) by multiplying these two factors of
n. Practically this is useful for problem for small input size or elementary
sorting algorithms. The worst case time complexity for Bubble sort, Insertion
sort, Selection sort and insertion sort running time complexities are O(n2)
2
T(n)=n
11
Basics of An Algorithm And
Its Properties
4. Cubic Time: (T(n)= O(n3)): It often occurs when the algorithm is
having there nested loops and each loop has a maximum n iterations.
Let us have one interesting example which requires cubic time
complexity. Suppose we are given n sets: 𝑆 , 𝑆 ,….𝑆 . Size of each set
is n (ie each set is having n elements). The problem is to find whether
some pairs of these sets are disjoint, i.e there are no common elements
in these pairs and what is the time complexity ?
T(n)=
12
Introduction to Algorithms
the complexity of running time we have to find how many distinct
subsets of a size k of n elements of a set can be chosen. For that we
have to take a combination of n elements taken k at a time .As an
example let us consider a problem to find an independent set in a graph
which can be defined as a set of nodes in which no pair of nodes have
an edge between them. Let us formulate the independent set problem in
the following way: given a constant k and a graph G having n nodes
(vertices) find out an independent set of a size k.
The brute force method to solve this problem would require searching
for all subsets of k nodes and for each subset it would examine whether
there is an edge connecting any two nodes for each subset s of a size k
.Below is a pseudo-code for finding an independent set.
Pseudo-code
for each subset s of a size k in a graph G
check whether s is an independent set
if yes, print “ s is an independent set
else stop
In this case the outer loop will iterate O(nk) times and it selects all k-
node subsets of n node of the graph. In the inner loop within each
subset it loops for each pair of nodes to find out whether there is an
edge between the pair which will require O( 2 out of k)
pairs of search i.e. O(k2) search. Therefore the total time now is
O(k2nk). Since k is a constant, it can be dropped, finally it is O(nk).
k
T(n)=n
Input G(V,E)
{
for each subset s of n number of nodes
verify whether s is an independent set
if s is the largest among all the subsets examined so for
print “s is the largest independent set ”
end if
end for
}end of code fragment
n
T(n)=k
Verification of all pairs of subsets i.e. (2n) whether these subsets are
having edges or not and then selecting the maximum will be O(n2) i.e
the total number of pair of subsets. The total running time would be
14
Introduction to Algorithms
O(n2*2n).O(2n)running time complexity arises when a search algorithm
considers all subsets of n elements.
(ii) O(n!) also occurs where the algorithm requires arranging n elements
into a particular order (i.e. a permutation of n numbers). A classic
example is travelling salesman problem. Given a n number of cities
with distance between all pairs of cities with the following conditions
(i) the salesman can start the tour with any city but must conclude the
tour with the starting city only (ii) all cities must be visited only once
except the one where from the tour starts. The problem is to find out
the shortest tour covering all n cities. Applying a brute force approach
to find out the solution, a salesman has to explore n! searches which
will take O(n!). Note that a salesman can pick up any city among n
cities to start the tour. Next it will have (n-1) cities to pickup the second
city on the tour. There will be (n-2) cities to pick up the third city at the
next stage and so forth. Multiplying all these choices we get n! i.e. n (n-
1) (n-2) ....(2) (1)
Suppose M is an algorithm with n the input data size. The time and space used
by the algorithm M are the two main measures for the efficiency of M. The
time is measured by counting the number of key operations, for example, in
case of sorting and searching algorithms, the number of comparisons is the
15
Basics of An Algorithm And
Its Properties
number of key operations. That is because key operations are so defined that
the time for the other operations is much less than or at most proportional to
the time for the key operations. The space is measure
measured d by counting the
maximum of memory needed by the algorithm.
The complexity of an algorithm M is the function f(n), which give the running
time and/or storage space requirement of the algorithm in terms of the size n of
the input data. Frequently, the stor
storage
age space required by an algorithm is simply
a multiple of the data size n. In general the term ““complexity
complexity” given anywhere
simply refers to the running time of the algorithm. There are 3 cases, in
general, to find the complexity function f(n):
Best case: Clearly the best case occurs when x is the first element in the array
A. That is . In this case
Worst case: Clearly the worst case occurs when x is the last element in the
array A or is not present in given array A (to ensure this we have to search
entire array A till last element). In this case, we have
.
Average case: Here we assume that searched element appear in array A, and
it is equally likely to occur at any position in the array. Here the number of
comparisons can be anyofnumbers1,2,3,…,n, and each number occurs with the
probability p=1/n then
There are three basic asymptotic(i.e., when input size n → infinity) notations
which are used to express the running time of an algorithm in terms of
function, whose domain is the set of natural numbers N={1,2,3,…..}. These
are:
Asymptotic notation gives the rate of growth, i.e. performance, of the run time
for “sufficiently large input sizes” and is not a measure of the
particular run time for a specific input size (which should be done
empirically). O-notation is used to express the Upper bound (worst case); Ω-
notation is used to express the Lower bound (Best case) and Θ- Notations is
used to express both upper and lower bound (i.e. tight bound) on a function.
17
Basics of An Algorithm And
Its Properties
We generally want to find either or both an asymptotic lower bound and upper
bound for the growth of our function.
The types of problems in computing are limitless, and are categorized into a
few areas to make it easy for researchers to address types of problems while
addressing the algorithm field.
Following are the some commonly known problem types:
Sorting
Searching
Graph problems
Combinatorial problems
Geometric problems
Numerical problems
For the above-mentioned categories, certain standard input sets are defined as
benchmarking sets to analyse the algorithms.
Sorting
The sorting is the process to arrange the given set of items in a certain order,
assuming that the nature of the items allow such an ordering. For example,
sorting a set of numbers in increasing or decreasing order and sorting the
character strings, like names, in an alphabetical order.
1. Stability
2. In-place.
A sorting algorithm is called stable if it does not change the relative positions
of any two equal items of input list. Say, in an input list, there are two equal
18
Introduction to Algorithms
item sat positions i and j where i< j, then the final position of these items in the
sorted list should also be k and l respectively, such that k<l. That is there
should not be any swapping among these equal items and should not
interchange their position with each other.
A sorting algorithm needs extra memory space to store elements during the
swapping process. For small set of items in a list, this constraint is not
observable but, for an input list of large elements the required storage space is
considerable large. An algorithm is said to be in-place if the required extra
memory is not markable.
Searching
Searching is finding an element, referred as search key, in a given set of items
(may have the redundant value). Searching is one of the most important and
frequently performed operation on any dataset/database.
String Processing
Exponential increase in the textual data due to the various applications over
social media and blogs, string-handling algorithms become a current area of
research. Another reason for blooming strings rather text processing is the kind
of data available. Now day’s the business paradigms are totally changed from
offline to online. According to Grant Thornton, e-commerce in India is
expected to be worth US$ 188 billion by 2025.Most of the text data is used to
predict the interest of people involving direct or indirect monetary benefits for
commercial organizations specially e-commerce sectors. One of the most
widely used search engine (Google) is also based on string processing.
Graph Problems
It is always favourable for researchers to map a computational problem to a
graph problem. Many computational problems can be solved using graph.
Most of the computer network problems can be solved using graph algorithms
efficiently. Problems like: visiting all the nodes of a graph (broadcasting in
network), routing in networks (finding the minimum cost path, i.e. the shortest
19
Basics of An Algorithm And
Its Properties
path, path with minimum delay etc. can be solved efficiently with graph
algorithms.
At the same time some of the graph problems are computationally not easy,
like the travelling salesman and the graph-colouring problems. The Travelling
Salesman Problem (TSP) is used to cover n cities by taking the shortest path
and not visiting any of the city more than once. The graph-colouring
problem seeks to colour all the vertices of a graph with minimum number
colours such that, no two adjacent vertices having the same colour. While
solving TSP cities can be considered as the vertices of the graph. Event
scheduling could be one of the problems which can be solved using graph
colouring algorithm. Considering events to be represented by the vertices,
there exists an edge between two events only if the corresponding events
cannot be scheduled at the same time.
Combinatorial Problems
These types of problems have a combination of solutions i.e. more than one
solution are possible. The aim of the combinatorial problems is to find
permutations, combinations, or subsets, satisfying the given conditions. The
travelling salesman problem, independent set and the graph-coloring problems
can be categorized as examples of combinatorial problems. From both
theoretical as well as practical point of view, the combinatorial problems are
considered to be one of the most difficult problems in computing. Due to the
combinatorial type of solutions, it becomes very difficult to handle the
problems with big size inputs sets. The number of combinatorial objects (the
output solution) grows rapidly with the problem’s size.
Geometric Problems
Some of the applications of Geometric algorithms are computer graphics,
robotics and tomography. These algorithms are based upon geometric objects
such as points, lines, and polygons. The geometry procedures are developed to
solve various geometric problems, like construction shapes of geometric
objects, triangles, circles, etc., using ruler and compass.
The closest-pair problem is to find the closest pair out of a given set of points
in the plane.
Numerical Problems
20
Introduction to Algorithms
Problems of numerical computing nature are simultaneous linear equations
(linear algebra), differential equations, definite integration, and statistics.
Most of the numerical problems could be solved approximately.
Step 1. Divide the problem (top level) into a set of sub-problems (lower
level).
Step 2. Solve every sub-problem individually by recursive approach.
Step 3. Merge the solution of the sub-problems into a complete solution of
the problem.
Following are the examples of the problems that can efficiently be solved
using divide and conquer approach.
Binary Search.
Quick Sort.
Merge Sort.
Strassen's Matrix Multiplication.
Closest Pair of Points.
Greedy Technique
Using Greedy approach, optimization problems are solved efficiently. In an
optimization problem, the given set of input values are either to be maximized
or minimized (called as objective), subject to some constraints or conditions.
Greedy algorithm always picks the best choice (greedy approach) out of
many at a particular moment to optimize a given objective.
21
Basics of An Algorithm And
Its Properties
The greedy method chooses the local optimum at each step and this
decision may result in overall non-optimum or optimum solution.
The greedy approach doesn't always produce the optimal solution rather
produces very nearby solution to the optimal solution.
Consequently, Greedy algorithms are often very easy to design for the
optimisation problems. Following are some of the examples of the greedy
approach.
Dynamic Programming
Dynamic Programming approach is a bottom-up approach which involves
finding solution of all sub-problems, saving these partial results, and then
reusing them to solve larger sub-problems until the solution to the original
problem is obtained. Reusing the results of sub-problems (by maintaining a
table of results) is the major advantage of dynamic programming because it
avoids the re-computations (computing results twice or more) of the same
problem. Thus Dynamic programming approach takes much less time than
naïve or straightforward methods.
Randomized Algorithms
In a randomized algorithm, a random number is selected at any stage of the
solution and is used for computation of the solution, that’s why it is called as
randomized algorithm. In other words it can be said that algorithms that make
random choices for faster solutions are known as randomized algorithms. For
example, in the Quick sort algorithm, a random number can be generated and
considered as a pivot. In other example, a random number can be chosen as
possible divisor to factor a large number.
Backtracking Algorithm
Backtracking algorithm is like creating checkpoints while exploring new
solutions. It works analogues to depth-first search. It searches all the possible
solutions. During the exploration of solutions, if a solution doesn't work, it
back-track to the previous place and then find the other alternatives to get the
solution. If there are no more choice points the search fails.
1.10 SUMMARY
23
Basics of An Algorithm And
Its Properties
In computation, an algorithm is independent from a programming language.
Algorithm is designed to understand and analyze the solution of a
computational problem. In an algorithm, statements may be used to perform an
action called as sequencing, or to take decision (selection) or to repeat certain
actions (iterations).
In computing, based on the nature of the problem, it can be assigned any one
of the commonly known categories, namely sorting, searching, string
processing, graph problems, combinatorial problems, geometric problems,
numerical problems.
Similar type of problems can be solved with similar approach. Some of the
commonly used problems solving techniques are Brute Force and Exhaustive
search approach, Divide and Conquer approach, Greedy technique, Dynamic
Programming, Branch and Bound, Randomized algorithms, and Backtracking
algorithm.
S.
Set A S.N. Set B
N.
Arranging a list of numbers in
1 Sorting Problem A
ascending order.
Geometric
2 B Finding an item in set items.
Problem
Finding the shortest path between
3 Graph Problem C
two nodes.
Numerical Finding Euler graph for a given
4 D
Problem graph.
Searching Finding the solutions of a given set
5 E
Problem of linear equations.
Finding the pair of points (from a set
6 String Processing F of points) with the smallest distance
between them.
7 G Match a word in a paragraph.
1 – A, 2 – F, 3 – C, D, 4 – E, 5 – B, 6 – G.
25
Basics of An Algorithm And
Its Properties
For example, the next output of a card shuffling program of blackjack game
should not be predictable by players even if the source code of the program is
visible.
27
Introduction to Algorithms
UNIT 2 ASYMPTOTIC BOUNDS
Structure
2.0 Introduction
2.1 Objectives
2.2 Some Useful Mathematical Functions & Notations
2.2.1 Summation & Product
2.2.2 Function
2.2.3 Logarithms
2.3 Mathematical Expectation
2.4 Principle of Mathematical Induction
2.5 Efficiency of an Algorithm
2.6 Well Known Asymptotic Functions &Notations
2.6.1 The NotationΟ
2.6.2 NotationΩ
2.6.3 The NotationΘ
2.6.4 Some Useful Theorems for O, Ω, Θ
2.7 Summary
2.8 Solutions/Answers
2.9 Further Readings
2.0 INTRODUCTION
In the last unit, we have discussed about algorithms and its basic properties. We also
discussed about deterministic and stochastic algorithms. In this unit, we will discuss
the process to compute complexities of different algorithms, useful mathematical
functions and notations, principle of mathematical induction, and some well known
asymptotic functions. Algorithmic complexity is an important area in computer
science. If we know complexities of different algorithms then we can easily answer
the following questions-
The above-mentioned criterions are used as the basis of the comparison among
different algorithms. With the help of algorithmic complexity, programmers improve
the quality of their code using relevant data structures. To measure the efficiency of a
code/ algorithm, asymptotic notations are normally used. Asymptotic notations are the
mathematical notations that estimate the time or space complexity of an algorithm or
program as function of the input size. For example, the best-case running time of a
function that sorts a list of numbers using bubble sort will be linear i.e., O(n). On the
contrary, the worst- case running time will be O(n2). So, we can say that the bubble
sort takes T(n) time, where, T(n)=O(n2). The asymptotic behavior of a function f(n)
indicates the the growth of f(n) as n gets very large. The small values of n are
generally ignored as we are interested to know how slow the program or algorithm
will be on large input. The slower asymptotic growth rate, the better the algorithm
performance. As per this measurement, a linear algorithm (i.e., f(n)=d*n+k) is always
asymptotically better than a quadratic one (e.g., f(n)=c*n2+q) for any positive value of
1
Asymptotic Bounds
c, k, d, and q. To understand concepts of asymptotic notations, you will be given a
idea of lower bound, upper bound, and an average bound. Mathematical induction
plays an important role in computing the algorithms’ complexity. Using the
mathematical induction, problem is converted in the form mathematical expression
which is solved to find the time complexity of algorithm. Further to rank algorithms
in increasing or decreasing order asymptotic notations such as big oh, big omega, and
big theta are used.
2.1 OBJECTIVES
Unless mentioned otherwise, we use the letters N, I and R in the following sense:
N = {1, 2, 3, …}
I = {…, ─ 2, ─, 0, 1, 2, ….}
R = set of Real numbers.
Summation:
Sum of sequences
( )
(i) ∑ 𝑖 = 1+2 +⋯𝑛 =
( )( )
(ii) ∑ 𝑖 = 1 + 2 + ⋯𝑛 =
( )
(iii) ∑ 𝑖 = 1 + 2 + 3 + ⋯𝑛 =
Product
2
Introduction to Algorithms
The expression
1 2 …n
can be denoted in shorthand as
2.2.2 Function:
For two given sets A and B a rule f which associates with each element of A, a
unique element of B, is called a function from A to B. If f is a function from a set A to
a set B then we denote the fact by f: A B. For example the function f which
associates the cube of a real number with a given real number x, can be written as
𝑓(𝑥) = 𝑥
Suppose the value of x is 2 there f maps 2 to 8
Floor Function: Let x be a real number. The floor function denoted as xmaps each
real number x to the integer, which is the greatest of all integers less than or equal to
x.
Ceiling Function: Let x be a real number. The ceiling function denoted as xmaps
each real number x to the integer, which is the least of all integers greater than or
equal to x.
x ─1 < x xx< x + 1.
2.2.3 Logarithms
Logarithms are important mathematical tools which are widely used in analysis of
algorithms.
The following important properties of logarithms can be derived from the properties
of exponents. However, we just state the properties without proof.
It general the logarithms of any number x is the power to which another number a,
called the base, must be raised to produce x. Both a & x are positive numbers.
Definition
b mod n: if n is a given positive integer and b is any integer, then
b mod n = 42 mod 11 = 9.
If b = ─42andn = 11then
Example 2.1: Suppose, the students of MCA, who completed all the courses in the
year 2005, had the following distribution of marks.
0% to 20% 08
20% to 40% 20
40% to 60% 57
60% to 80% 09
80% to 100% 06
If a student is picked up randomly from the set of students under consideration, what is
the % of marks expected of such a student? After scanning the table given above, we
intuitively expect the student to score around the 40% to 60% class, because, more
than half of the students have scored marks in and around this class.
4
Introduction to Algorithms
Assuming that marks within a class are uniformly scored by the students in the class,
the above table may be approximated by the following more concise table:
Thus, we assign weight (8/100) to the score 10% (8, out of 100 students, score on
the average 10% marks); (20/100) to the score 30% and so on.
Thus
The final calculation of expected marks of 47 is roughly equal to our intuition of the
expected marks, according to our intuition, to be around 50.
We generalize and formalize these ideas in the form of the following definition.
Mathematical Expectation
For a given set S of items, let to each item, one of the n values, say, v1, v2,…,vn, be
associated. Let the probability of the occurrence of an item with value vi be pi. If an
item is picked up at random, then its expected value E(v) is given by
E(v) = p v = p .v + p .v + ⋯…… p .v
Induction plays an important role to many facets of data structure and algorithms. In
general, all correctness opinions are based on induction principle.
5
Asymptotic Bounds
value (base case). It is the proof that the statement is true for n = 1 or some other
starting value.
2. Induction Hypothesis- it is the assumption that the statement is true for any value
of n where n ≥1
3. Induction Step- In this stage we make a proof that if the statement is true for n , it
must be true for n+1
𝐧(𝐧 𝟏)
Example 1: Write a proof that the sum of the first n positive integers is , that
𝟐
is
𝐧(𝐧 𝟏)
𝟏 + 𝟐 + ⋯…+ 𝐧 = 𝟐
.
Base Step): We must show that the given equation is true for n=1
( )
i.e.1 = = 1 ⟹ this is true.
Hence we proved that the first statement is true for n = 1
Induction Hypothesis: Let us assume that the given equation is true for any value of
n (n ≥ 1)
( )
that is 1 + 2 + ⋯ … + n = ;
Induction Step: Now we have to prove that it is true for (n+1).
Consider
( )[( ) ]
1 + 2 + 3 + ⋯ … … + n + (n + 1) =
In view of the above explanation, the notion of size of an instance of a problem plays
an important role in determining the complexity of an algorithm for solving the
problem under consideration. However, it is difficult to define precisely the concept of
size in general, for all problems that may be attempted for algorithmic solutions. In
some problems number of bits is required in representing the size of an instance.
However, for all types of problems, this does not serve properly the purpose for which
the notion of size is taken into consideration. Hence different measures of size of an
instance of a problem are used for different types of problems. Let us take two
examples:
(i) In sorting and searching problems, the number of elements, which are to be sorted
or are considered for searching, is taken as the size of the instance of the problem of
sorting/searching.
(ii) In the case of solving polynomial equations or while dealing with the algebra of
polynomials, the degrees of polynomial instances, may be taken as the sizes of the
corresponding instances.
To measure the efficiency of an algorithm, we will consider the theoretical approach
and follow the following steps:
Calculation of time complexity of an algorithm- Mathematically determine the
time needed by the algorithm, for a general instance of size, say, n of the problem
under consideration. In this approach, generally, each of the basic instructions like
assignment, read and write, arithmetic operations, comparison operations are assigned
some constant number of (basic) units of time for execution. Time for looping
statements will depend upon the number of times the loop executes. Adding basic
units of time of all the instructions of an algorithm will give the total amounts of time
of the algorithm
The approach does not depend on the programming language in which the
algorithm is coded and on how it is coded in the language as well as the
computer system used for executing(a programmed version of) the algorithm.
But different computers have different execution speeds. However, the speed
of one computer is generally some constant multiple of the speed of the other
Instead of applying the algorithm to many different-sized instances, the
approach can be applied for a general size say n of an arbitrary instance of the
problem but the size n may be arbitrarily large under consideration.
An important consequence of the above discussion is that if the time taken by one
machine in executing a solution of a problem is a polynomial (or exponential)
function in the size of the problem, then time taken by every machine is a polynomial
(or exponential) function respectively, in the size of the problem.
In the next section we will examine the asymptotic approach to analyze the efficiency
of algorithms
7
Asymptotic Bounds
algorithms in the worst case takes T(n) = n2 where n is a size of the list . In contrast,
Merge sort takes time T (n) = n*log2(n) .
The asymptotic behavior of a function f(n) (such as f(n)=c*n or f(n)=c*n2, etc.) refers
to the growth of f(n) as n gets very large. Small values of n are not considered. The
main concern in asymptotic analysis of a function is in estimating how slow the
program will be on large inputs. One should always remember: the slower the
asymptotic growth rate, the better the algorithm. The Merge sort algorithm is better
than sorting algorithms. Binary search algorithm is better than the linear searching
algorithm. A linear algorithm is always asymptotically better than a quadratic one .
Remember to think a very large input size when working with asymptotic rates of
growth. If the relative behaviors of two functions for smaller values conflict with the
relative behaviors for larger values ,then we may ignore the conflicting behaviors for
smaller values.
For example, let us consider the time complexities of two solutions of a problem
having input size n as given below:
𝑇 (n) = 1000 𝑛
𝑇 (n) = 5𝑛
Despite the fact 𝑇 (n) ≥ 𝑇 (n) for n ≤ 14, we would still prefer the solution as 𝑇 (n) as
the time complexity because
O(1) constant
O(log n) logarithmic
O(n) linear
O(n log n) "n log n"
O(n2) quadratic
3
O(n ) cubic
O(𝑛 ) polynomial
O(2 ) exponential
Consider a linear search algorithm. The worst case of the algorithm is when the
element to be searched for is either not in the list or located at the end of the list. In
this case the algorithm runs for the longest possible time. It will search the entire list.
If an algorithm runs in time T(n), we mean that T(n) is an upper bound on the running
time that holds for all inputs of size n. This is called worst-case analysis.
8
Introduction to Algorithms
sequence of length n is proportional to n2 but whose average running time is
proportional to n log n.
Let us consider two standard sorting algorithms : The first takes 1000 𝑛
and the second takes 10 𝑛 time in the worst case respectively on a machine.
Both of these algorithms are asymptotically same (order of growth is𝑛 ).
Since we ignore constants in asymptotic analysis, it is difficult to judge
which one is more suitable.
Worst case versus average performance
If an algorithm A has better worst case performance than the algorithm B, but
the average performance of B given the expected input is better, then B could
be a better choice than A.
There are mainly three asymptotic notations if we do not want to get involved with
constant coefficients and less significant terms. These are
1. Big-O notation,
2. Big-Θ ( Theta) notation
3. Big-Ω (Omega) notation
Let and are two positive functions , each from the set of natural
numbers (domain) to the positive real numbers.
: n ≥n0
9
Asymptotic Bounds
The above function is still a quadratic algorithm and can be written as:
<= (3 +4 -2) n2
= O(𝑛 )
One important advantage of big-O notation is that it makes algorithms much easier to
analyze, since we can conveniently ignore low-order terms and constants
2. Show n3 != O(n2).
However, it will never be possible, thus the statement that n3 = O(n2) must be
incorrect.
Big Omega () describes the asymptotic lower bound of an algorithm whereas a big
Oh(O)notation represents an upper bound of an algorithm. Generally we say that an
algorithm takes at least this amount of time without mentioning the upper bound. In
such case, big-() notation is applied. Let's define it more formally:
10
Introduction to Algorithms
f(n) = (g(n)) if and only if there exists some constants C and 𝑛 such that f(n)
C.g(n) : n ≥ 𝑛 . The following graph illustrates the growth of f(n) = (g(n))
As shown in the above graph f(n) is bounded from below by C.g(n).Note that for all
values of f(n) always lies on or above g(n).
If f(n) is Ω(g(n)) which means that the growth of f(n) is asymptotically no slower than
g(n) no matter what value of n is provided.
Example 1
: show that
Hence .
In case the running time of an algorithm is Θ(n), it means that once n gets large
enough, the running time is minimum c1⋅n, and maximum c2⋅n, where c1 and c2 are
constants. It provides both upper and lower bounds of an algorithm. The following
figure illustrates the function f(n) = Θ(g(n). As shown in the figure the value of f(n)
lies between c1(g(n)) and c2(g(n))for sufficiently large value of n.
11
Asymptotic Bounds
Now let us define the theta notation: for a given function g(n) and constants C1,C2
and 𝑛 where n0>0, C1>0, and C2>0, (g(n)) can be denoted as a set of functions such
that the following condition is satisfied:
0 <= C1g(n) <= f(n) <= C2g(n) for all n >= n0
The above inequalities represent two conditions to be satisfied simultaneously viz., C1
g(x) f(x) and f(x) C2 g(x))
Theorem: For any two functions f(x) and g(x), f(x) = (g(x)) if and only if
f(x) = O (g(x)) and f(x) = (g(x)).
if f(n) is Θ(g(n)) this means that the growth of f(n) is asymptotically at the
same rate as g(n) or we can say the growth f(n) is not asymptotically
The following theorems are quite useful when you are dealing (or solving problems)
with O, and
Proof:𝑓(𝑛) = 𝑎 𝑛 + 𝑎 𝑛 + ⋯………+ 𝑎 𝑛 + 𝑎
= 𝑎 𝑛
𝑓 (𝑛 ) ≤ |𝑎 |𝑛
≤𝑛 |𝑎 |𝑛 ≤𝑛 |𝑎 |for𝑛 ≥ 1
12
Introduction to Algorithms
Let us assume |𝑎 | + |𝑎 | + ⋯ … … … + |𝑎 | + |𝑎 | = 𝑐
Proof: 𝑓(𝑛) = 𝑎 𝑛 + ⋯ … … … . 𝑎 𝑛 + 𝑎
𝑓(𝑛) = 𝑂 (𝑛 ) … … … . (1)
Example 1: By applying theorem, find out the O-notation, Ω-notation and Θ-notation
for the following functions.
(i) 𝑓(𝑛) = 5𝑛 + 6𝑛 + 1
(ii) 𝑓(𝑛) = 7𝑛 + 2𝑛 + 3
Solution:
(i) Here The degree of a polynomial f(n) is, m = 3, So by Theorem 1, 2
and 3:
𝑓(𝑛) = 𝑂(𝑛 ), 𝑓(𝑛) = Ω (n )and 𝑓(𝑛) = 𝛩(𝑛 ),
Let f(n) and g(n) be two asymptotically positive functions. Prove or disprove the
following (using the basic definition of O, Ω andΘ):
a) 4𝑛 + 7𝑛 + 12 = 𝑂(𝑛 )
b) 𝑙𝑜𝑔𝑛 + log(𝑙𝑜𝑔𝑛) = 𝑂(𝑙𝑜𝑔𝑛)
c) 3𝑛 + 7𝑛 − 5 = 𝛩(𝑛 )
d) 2 = 𝑂(2 )
e) 2 = 𝑂(2 )
f) 𝑓(𝑛) = 𝑂 𝑔(𝑛) 𝑖𝑚𝑝𝑙𝑖𝑒𝑠 𝑔(𝑛) = 𝑂 𝑓(𝑛)
g) max{f(n), g(n)} = 𝛩 𝑓(𝑛) + 𝑔(𝑛)
( ) ( )
h) 𝑓(𝑛) = 𝑂 𝑔(𝑛) 𝑖𝑚𝑝𝑙𝑖𝑒𝑠 2 =𝑂 2
i) 𝑓(𝑛) + 𝑔(𝑛) = 𝛩(min 𝑓(𝑛), 𝑔(𝑛)
13
Asymptotic Bounds
j) 33𝑛 + 4𝑛 = Ω(𝑛 )
k) 𝑓(𝑛) + 𝑔(𝑛) = 𝑂(𝑛 ) 𝑤ℎ𝑒𝑟𝑒
f(n) =2𝑛 − 3𝑛 + 5 𝑎𝑛𝑑 𝑔(𝑛) = 𝑛𝑙𝑜𝑔𝑛 + 10
(
2.7 SUMMARY
To that end,
1 + 2 + ⋯ + (𝑛 + 1) = 1 + 2 + ⋯ + 𝑛 + (𝑛 + 1)
𝑛(𝑛 + 1)(2𝑛 + 1)
= + (𝑛 + 1)
6
𝑛(𝑛 + 1)(2𝑛 + 1) + 6(𝑛 + 1)
=
6
(𝑛 + 1)(2𝑛 + 𝑛 + 6𝑛 + 6)
=
6
14
Introduction to Algorithms
(𝑛 + 1)(2𝑛 + 7𝑛 + 6)
=
6
(𝑛 + 1)(𝑛 + 2)(2𝑛 + 3)
=
6
(𝑛 + 1)[(𝑛 + 1) + 1][2(𝑛 + 1) + 1]
=
6
Questioin2: Prove that for all nonnegative integers n,
2 +2 +2 +⋯+2 = 2 − 1.
2 =2 −1
To that end,
2 + 2 + 2 +⋯+ 2 = 2 + 2 +2 + ⋯+ 2 + 2
=2 −1+2
= 2(2 ) − 1
= 2( ) − 1.
a) 4𝑛 + 7𝑛 + 12 = 𝑂(𝑛 )
(4𝑛 + 7𝑛 + 12) ≤ 𝑐, 𝑛 … … … (1)
for c=5 and n≤9; the above inequality (1) is satisfied.
Hence 4𝑛 + 7𝑛 + 12 = 𝑂(𝑛 ).
c) 3𝑛 + 7𝑛 − 5 = Θ(𝑛 )
3𝑛 + 7𝑛 − 5 = Θ(𝑛 );
To show this, we have to show:
15
Asymptotic Bounds
𝐶 . 𝑛 ≤ 3𝑛 + 7𝑛 − 5 ≤ 𝐶 . 𝑛 … … … (∗)
(i) L.H.S inequality
𝐶 . 𝑛 ≤ 3𝑛 + 7𝑛 − 5 … … (1)
This is satisfied for 𝐶 = 1andn ≥ 2
(ii) R.H.S inequality
3𝑛 + 7𝑛 − 5 ≤ 𝐶 . 𝑛 … … (2)
This is satisfied for 𝐶 = 1 𝑎𝑛𝑑 𝑛 ≥ 1
inequality (*) is simultaneously satisfied for
𝐶 = 1, 𝐶 = 10 𝑎𝑛𝑑 𝑛 ≥ 2
d) 2 = 𝑂(2 )
2 ≤ 𝐶. 2 ⟹2 ≤ 2. 2
e) 2 = 𝑂(2 )
2 = ≤ 𝐶. 2
4 ≤ 2. 2 ……(1)
No value of C and n0Satisfied this in equality (1)
2 ≠ 𝑂(2 ).
16
Introduction to Algorithms
max{f(n), g(n)} ≤ C1. (f(n) +g(n) ………(2)
This inequality (2) is satisfied for C2= 1 and n ≥ 1
inequality (*) is simultaneously satisfied for
1
𝐶 = , 𝐶 = 1 𝑎𝑛𝑑 𝑛 ≥ 1
2
Remark: Let f(n) =n and g(n) =𝑛 ;
then max{n,𝑛 } = 𝛩 (𝑛 + 𝑛 )
𝑛 = Θ(𝑛 ); which is TRUE (by de inition of Θ)
( ) ( )
h) 𝑓(𝑛) = 𝑂 𝑔(𝑛) 𝑖𝑚𝑝𝑙𝑖𝑒𝑠 2 =𝑂 2
( ) ( )
𝑁𝑜; 𝑓(𝑛) = 𝑂 (𝑔(𝑛)𝑑𝑜𝑒𝑠 𝑛𝑜𝑡 𝑖𝑚𝑝𝑙𝑖𝑒𝑠 2 =𝑂 2 ;
we can prove this by taking a counter Example ;
Let 𝑓(𝑛) = 2𝑛 𝑎𝑛𝑑 𝑔(𝑛) = 𝑛, we have
2 = 𝑂(2 ); which is not TRUE[𝑠𝑖𝑛𝑐𝑒 2 = 4 ≠ 𝑂(2 )].
j) 33𝑛 + 4𝑛 = Ω(𝑛 )
(33𝑛 + 4𝑛 ) ≥ 𝐶. 𝑛 ;
There is no positive integer for C and n
which satisfy this inequality. Hence (33𝑛 + 4𝑛 ) ≠ 𝐶. 𝑛 .
17
Introduction to Algorithms
UNIT 3 COMPLEXITY ANALYSIS OF SIMPLE
ALGORITHMS
Structure Page Nos.
3.0 Introduction
3.1 Objectives
3.2 A Brief Review of Asymptotic Notations
3.3 Analysis Of Simple Constructs Or Constant Time
3.4 Analysis of Simple Algorithms
3.4.1 A Summation Algorithm
3.4.2 Polynomial Evaluation Algorithm
3.4.3 Exponent Evaluation
3.4.4 Sorting Algorithm
3.5 Summary
3.6 Solutions/Answers
3.7 Further Readings
3.0 INTRODUCTION
3.1 OBJECTIVES
1
Complexity Analysis of
Simple Algorithms
The complexity analysis of algorithm is required to measure the time and space
required to run an algorithm. In this unit we focus on only the time required to execute
an algorithm. Let us quickly review some asymptotic notations (Please refer to the
previous unit for detailed discussion)
The central idea of these notations is to compare the relative rate of growth of
functions.
(i) 𝑇(𝑛) = 𝑂 𝑓(𝑛) if there are two positive constants C and n0 such
that𝑇(𝑛) ≤ 𝐶𝑓(𝑛)where n ≥ 𝑛
(ii) 𝑇(𝑛) = Ω 𝑓(𝑛) if there are two positive constants C and n0 such that
𝑇(𝑛) ≥ CΩ f(n) where n ≥ n
(iii) 𝑇(𝑛) = 𝜃 𝑓(𝑛) if and only if 𝑇(𝑛) = O 𝑓(𝑛) 𝑎𝑛𝑑𝑇(𝑛) = Ω 𝑓(𝑛)
The second definition, 𝑇(𝑛) = Ω 𝑓(𝑛) says that the growth rate of T(n) is faster
than or equal to (≥) f(n).
Ex. 𝑖𝑛𝑡 𝑥;
𝑥 = 𝑥 + 5
𝑥 = 𝑥 −5
2) O(n): This is running time of a single looping statement which
includes comparing time, increment or decrement by some constant
value looping statement.
// Here c is a positive integer constant
for (i = 1; i <= n; i += c) {
// simple statement(s)
2
Introduction to Algorithms
}
code fragment of
if – else is
if (condition)
statement 1
else
statement 2
1. int i, tempresult;
2. tempresult =0;
3. for (i=1 ; I <=n; i++)
4. tempresult = tempresult + i * i * i
5. return tempresult;
Line# 3- The for loop has several unit costs: initializing i, cost for testing i<=n
(n+1 unit cost) and cost of incrementing i(1 unit of cost) Total cost is 2n +2
Line# 4- 2units of time for multiplication, 1 unit for addition and one unit of
time for assignment operation in one cycle. Therefore the total cost of this line
is 4n
Line# 5- It will take 1 unit of time. Overall cost will be = 6n+6 which is
written as O(n).
4
Introduction to Algorithms
3.4.2 Polynomial Evaluation
Struct polynomial{
int coefficient;
int exponent;
};
P(x)=15∗x∗x∗x∗x+17∗x∗x∗x−12∗x∗x+13∗x+16
Horner’s method:
P(x)=(((15∗x+17)∗x−12)∗x+13)∗x+16
Please observe the basic operations are: multiplication, addition and
subtraction. Since the number of additions and subtractions are the same in
both the solutions, we will consider the number of multiplications only in
worst case analysis of both the methods.
[The general form of a polynomial of degree n, and express our result in
terms of n. We’ll look at the worst case (maximum number of
multiplications) to get an upper bound on the work]
P(x)=anxn+an-1xn-1+…..+a1x1+a0x0
5
Complexity Analysis of
Simple Algorithms
(i) Analysis of Brute Force Method
A brute force approach to evaluate a polynomial is to evaluate all terms one by one.
First calculate xn, multiply the value with the related coefficient 𝑎 ,repeat the same
steps for other terms and return the sum
+a2∗x∗x∗+a1∗x+a0
In the first term, it will take n multiplications, in the second term n-1
multiplications, in the third term it takes n-2multiplications….. In the last
two terms: a2∗x∗x∗and a1∗xit takes 2 multiplications and 1
multiplicationaccordingly.
=n(n+1)/2= O( 𝑛 )
P(x)=(…(((an∗x+an−1)∗x+an−2)∗x+...+a2)∗x+a1)∗x+a0
In the first term it takes one multiplication, in the second term one multiplication, in
the third term it takes one multiplication …. . Similarly in all other terms it will take
one multiplication.
T(n) = ∑ 1 =n
T(n)=n
6
Introduction to Algorithms
7. final polynomial value at x is p.
StepII.AlgorithmtoevaluatepolynomialatagivenpointxusingHorner’srule:
Evaluate_Horner (a,n,x)
{
p = A[n];
for (i = n-1; i≤0;i--)
p = p * x + A[i];
return p;
}
follows
At x=3,
p(x) = (3x+5)x+6
p(2)=(9+5).3+6
= (14).3+6
=42+6
=48
Complexity Analysis
First step is one initial assignment that takes constant time i.e O(1).
For loop in the algorithm runs for n iterations, where each iteration cost
O(1) as it includes one multiplication, one addition and one assignment
which takes constant time.
7
Complexity Analysis of
Simple Algorithms Hence total time complexity of the algorithm will be O(n) for a polynomial of
degree n.
3. Write basic algorithm to evaluate a polynomial and find its complexity. Also
compare its complexity with complexity of Horner’s algorithm.
………………………………………………………………………………………
………………………………………………………………………………………
………………………………………………………………………………………
MATRIX (N X N)MULTIPLICATION
Matrix is very important tool in expressing and discussing problems which arise
from real life cases. By managing the data in matrix form it will be easy to
manipulate and obtain more information. One of the basic operations on matrices
is multiplication.
In this section matrix multiplication problem is explained in two steps as we have
discussed GCD and Horner’s Rule in previous section. In the first step we will
brief pseudo code and in the second step the algorithm for the matrix
multiplication will be discussed. This algorithm can be easily coded into any
programming language.
Further explanation of the algorithm is supported through an example.
Let us define problem of matrix multiplication formally, then we will discuss how
to multiply two square matrix of order n x n and find its time complexity. Multiply
two matrices A and B of order n*n each and store the result in matrix C of order
n*n.
8
Introduction to Algorithms
This matrix A has 3 rows and 3 columns.
Step I : Pseudo code: For Matrix multiplication problem where we will multiply two
matrices A and B of order 3x3 each and store the result in matrix C of order 3x3.
1. Multiply first row first element of first matrix with first column first element
of second matrix.
2. Similarly perform this multiplication for first row of first matrix and first
column of second matrix. Now take the sum of these values.
3. The sum obtained will be first element of product matrix C
4. Similarly Compute all remaining element of product matrix
C.
C= A x B
Step II : Algorithm for multiplying two square matrix of order n x n and find the
product matrix of order n x n
Matrix_Multiply(A,B,C,n)
{
1 2 3
A= 2 3 4
4 5 6
1 1 1
B= 2 3 2
3 2 1
= 14 13 8
20 19 12
9
Complexity Analysis of
32 31 20
Simple Algorithms
Complexity Analysis
First step is, for loop that will be executed n number of times i.e. it will take O(n)
time. The second nested for loop will also run for n number of time and will take
O(n) time.
Assignment statement inside second for loop will take constant time i.e. O(1) as it
includes only one assignment.
The third for loop i.e. innermost nested loop will also run for n number of times
and will take O(n ) time . Assignment statement inside third for loop will cost
O(1) as it includes one multiplication, one addition and one assignment which
takes constant time.
Hence, total time complexity of the algorithm will be O(n3) for matrix multiplication
of order n*n.
1. Write a program in ‘C’ to find multiplication of two matrices A[3x3] and B[3x3].
………………………………………………………………………………………….
………………………………………………………………………………………….
………………………………………………………………………………………….
3.4.3 EXPONENTEVALUATION
41=4
42=(41)2=42=16
44=(42)2=162=256
48=(44)2=2562=65,536
Therefore the final answer for 411, we only need to multiply three of them (skipping
10
Introduction to Algorithms
44 because the corresponding bit in 𝑛 is set to zero):411=65,536⋅16⋅4=4,194,304.
The time complexity of this algorithm is (log𝑛): to compute 𝑙𝑜𝑔𝑛 power of 𝑎 and then
to do almost log𝑛 multiplications to get the final result from them.
Computing xn at some point x = a i.e an tends to brute force multiplication of
a by itself n-1 times. So. To reduce the number of multiplication binary
exponentiation methods to compute xn will be discussed. Processing of
binary string for exponent n to compute xn can be done by following
methods:
left to right binary exponentiation
1. result=a
2. for i=s-2 to0
3. result = result *result
4. if A[i]= 1then
5. result= result *a
6. return result (i.e an)
Iteration 1:
i=3
result=a *a= a2
11
Complexity Analysis of
Simple Algorithms
A[3] ≠ 1
Iteration 2:
i=2
result= a2 * a2 = a4
A[2] ≠ 1
Iteration 3:
i=1
result= a4 * a4 = a8
A[1] ≠ 1
Iteration 4:
i=0
result= a8 * a8 = a16
A[0] = 1
result = a16 * a = a17
return a17
Hence
1. Set x =a
2. if A[0]= 1 then set result=a
3. else set result=1
4. Initialize i=1
5. compute x = x *x
6. if A[i] = 1 then compute result = result *x
7. Increment i by 1 as i=i+1 and if i is less than equal to s-1 then go to step4.
8. return computed value as result.
12
Introduction to Algorithms
1. x=a
2. if A[0]=1then
3. result =a
4. else
5. result=1
6. for i= 1 tos-1
7. x= x * x
8. if A[i]=1
9. result= result *x
10. return result (i.e an)
Step by step illustration of the right to left binary exponentiation algorithm for a 17 :
s=5, the length of binary string of 1’s and 0’s for exponent n
Iteration 1
i=1
x=a *a=
a2
A[1] ≠
1
Iteration 2
i=2
x= a2 * a2 = a4
A[2] ≠ 1
Iteration 3
i=3
x= a4 * a4 = a8
A[3] ≠ 1
Iteration 4
i=4
x= a8 * a8 = a16
A[4] = 1
result = result * x = a * a16 = a17
return a17
13
Complexity Analysis of
Simple Algorithms
In this example total number of multiplication is 5 instead of 16 multiplications in
brute force algorithm i.e n-1
From the above discussion we can conclude that the complexity for left to right
binary exponentiation and right to left binary exponentiation is logarithmic in terms
of exponent n.
1. Compute a283 using left to right and right to left binary exponentiation.
………………………………………………………………………………………
………………………………………………………………………………………
………………………………………………………………………………………
Linear Search
Linear_ Search( A[ ], X)
Step 1: Initialize i to 1
Step 2: if i exceeds the end of an array then print “element not found” and Exit
Step 3: if A[i] = X then Print “Element X Found at index i in the array” and
Exit
Step 4: Increment i and go to Step 2
We are given with a list of items. The following table shows a data set for
linear search:
7 17 3 9 25 18
In the above table of data set, start at the first item/element in the list and
compared with the key. If the key is not at the first position, then we move
from the current item to next item in the list sequentially until we either find
14
Introduction to Algorithms
what we are looking for or run out of items i.e the whole list of items is
exhausted. If we run out of items or the list is exhausted, we can conclude
that the item we were searching from the list is not present.
In the given data set key 25 is compared with first element i.e7 , they are not
equal then move to next element in the list and key is again compared with
17 , key 25 is not equal to 17. Like this key is compared with element in the
list till either element is found in the list or not found till end of the list. In
this case key element is found in the list and search is successful.
Let us write the algorithm for the linear search process first and then
analyze its complexity.
{
found=false // found is a boolean variable which will store either true or
false
for(i=0;i<n;i++)
{
if (a[i]==key)
found = true
break;
}
if (i==n)
found =
false
return found
}
For the complexity analysis of this algorithm, we will discuss the following
cases:
Best Case: The best case - we will find the key in the first place we look, at the
beginning of the list i.e the first comparison returns a match or return found as
15
Complexity Analysis of
Simple Algorithms true. In this case we only require a single comparison and complexity will be
O(1).
Worst Case: In worst case either we will find the key at the end of the list or
we may not find the key until the very last comparison i.e nth comparison.
Since the search requires n comparisons in the worst case, complexity will be
O(n).
Average Case: On average, we will find the key about halfway into the list;
that is, we will compare against n/2 data items. However, that as n gets larger,
the coefficients, no matter what they are, become insignificant in our
approximation, so the complexity of the linear search, is O(n). The average
time depends on the probability that the key will be found in the collection -
this is something that we would not expect to know in the majority of cases.
Thus in this case, as in most others, estimation of the average time is of little
utility.
Most of the times an algorithm run for the longest period of time as defined in
worst case. Information provide by best case is not very useful. In average
case, it is difficult to determine probability of occurrence of input data set.
Worst case provides an upper bound on performance i.e the algorithm will
never take more time than computed in worse case. So, the worst-case time
analysis is easier to compute and is useful than average time case.
3.4.4 SORTING
16
Introduction to Algorithms
- Internal Sort: - Internal sorts are the sorting algorithms in which the
complete data set to be sorted is available in the computer’s main memory.
- External Sort: - External sorting techniques are used when the collection
of complete data cannot reside in the main memory but must reside in
secondary storage for example on a disk.
In this section we will discuss only internal sorting algorithms. Some of the
internal sorting algorithms are bubble sort, insertion sort and selection sort.
For any sorting algorithm important factors that contribute to measure their
efficiency are the size of the data set and the method/operation to move the
different elements around or exchange the elements. So counting the
number of comparisons and the number of exchanges made by an algorithm
provides useful performance measures. When sorting large set of data, the
number of exchanges made may be the principal performance criterion,
since exchanging two records will involve a lot of time.
Bubble Sort
It is the simplest sorting algorithm in which each pair of adjacent elements is
compared and exchanged if they are not in order. This algorithm is not
recommended for use for a bigger size array because its average and worst
case complexity are of Ο(n2) where n is the number of elements in an array.
This algorithm is known as bubble sort, because the largest element in the
given unsorted array, bubbles up towards the last place in every cycle/pass .
First Pass
23 18 15 37 8 11
18 23 15 37 8 11
18 15 23 37 8 11
18 15 23 37 8 11
18 15 23 8 37 11
18 15 23 8 11 37
Second Pass
18 15 23 8 11 37
15 18 23 8 11 37
15 18 23 8 11 37
15 18 8 23 11 37
15 18 8 11 23 37
15 18 8 11 23 37
15 18 8 11 23 37
15 8 18 11 23 37
15 8 11 18 23 37
Third Pass
15 8 11 18 23 37
8 15 11 18 23 37
8 11 15 18 23 37
Fourth Pass
17
Complexity Analysis of
Simple Algorithms
8 11 15 18 23 37
8 11 15 18 23 37
Fifth Pass
8 11 15 18 23 37
In this the given list is divided into two sub list sorted and unsorted. The
largest element is bubbled from the unsorted list to the sorted sub list. After
each iteration/pass size of unsorted keep on decreasing and size of sorted
sub list gets on increasing till all element of the list comes in the sorted list.
With the list of n elements, n-1 pass/iteration are required to sort. Let us
discuss the result of iteration shown in above tables.
In pass 1, first and second element of the data set i.e 23 and 18 are compared
and as 23 is greater than 18 so they are swapped. Then second and third
element will be compared i.e 23 and 15, again 23 is greater than 15 so
swapped. Now 23 and 37 is compared and 23 is less than 37 so no swapping
take place. Then 37 and 8 is compared and 37 is greater than 8 so swapping
take place. At the end 37 is compared with 11 and again swapped. As a result
largest element of the given data set i.e 37 is bubbled at the last position in the
array. At each pass the largest element among the remaining elements in the
unsorted array bubbles up towards the sorted part of the array as shown in the
table above. This process will continue till n-1 passes.
The first version of the algorithm for above sorting method is as below:
Bubble Sort Algorithm- Version1
int i,j
for ( i= 1 to n-1
for (j = 0 to n-2
{
if (A[j]>A[j+1])
{
// swapping of two adjacent elements of an array A
exchange (A[j], A[j+1])
}
}
}
18
Introduction to Algorithms
T(n) = (n-1)(n-1)* C( constant time required for simple statements like
exchange)
T(n) = C𝑛 -2Cn + 1
T(n)= O(𝑛 )
Let us reanalyze the above algorithm to improve the running time algorithm
further. From the example it is visible that the Bubble sort algorithm divides
the array into unsorted and sorted sub-arrays. The inner loop rescans the
sorted sub- array in each cycle, although there will not be any exchange of
adjacent elements. The modified version (version 2) of the algorithm
overcomes this problem:
Version -2
int i,j
for ( i= 1 to n-1)
for (j = 0 to n-i-1)
{
if(A[j]>A[j+1])
{
// swapping of two adjacent elements of an array A
exchange(A[j], A[j+1])
}
}
}
There will be no change in the number of iterations i.e. n-2 iterations in the
first pass, but in the second pass it will be n-3, in the third pass it will be n-4
iterations and so on. In this case too, the complexity remains to be O(𝑛 ) but
the number of exchange operations will be less. This requires further
improvement of the algorithm.
In some cases there is no need of running n-1 passes in the outer loop. The
array might be sorted in less than that. The following is the modified version
(Version -3) of the algorithm
19
Complexity Analysis of
Simple Algorithms {
int i,j
for ( i= 1 to n-1)
{
flag = 0;
for (j = 0 to n-i-1)
{
if(A[j]>A[j+1])
{
// swapping of two adjacent elements of an array A
exchange( A[j], A[j+1])
flag = 1;
}
if (flag = = 0)
exit;
}
}
In case there is no swapping, flag will remain set to 0 and the algorithm will
stop running.
Time Complexity
In the modified algorithm, the inner loop will execute at least once to verify
that the array is sorted but not (n-i-1) times. Therefore the time complexity
will be:
T(n) = C* (n-1)
= O(n)
3.5 SUMMARY
Different versions of bubble sort algorithm are presented and its performance
20
Introduction to Algorithms
analysis is done at the end.
3.6 SOLUTIONS/ANSWERS
P(x)=anxn+an-1xn-1+…..+a1x1+a0x0
Iteration 1,
poly = x * 0 + a[4] = 3
Iteration 2,
poly = x * 3 + a[3] = 2 * 3 + 2 = 6 +2 = 8
Iteration 3,
poly = x * 8 + a[2]
= 2 * 8 + 0 = 16 + 0 = 16
Iteration 4,
poly = x * 16 + a[1]
= 2 * 16 + (-5) = 32 -5 = 27
Iteration 5,
poly = x * 27 + a[0]
= 2 * 27 + 7 = 54 + 7 = 61
function(a[n], n, x)
{
poly = 0;
result =1;
for (j=0; j<i; j++)
{
21
Complexity Analysis of
Simple Algorithms
result= result * x;
}
}
return poly.
}
#include<stdio.h>
int main()
{
int a[3][3],b[3][3],c[3][3],i,j,k,sum=0;
{
printf("\n");
for (j=0;j<3;j++)
printf("%d\t",b[i][j]);
}
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=0;
for(i=0;i<3;i++)
22
Introduction to Algorithms
{
for(j=0;j<3;j++)
{
sum=0;
for(k=0;k<3;k++)
sum=sum+a[i][k]*b[k][j];
c[i][j]=sum;
}
}
printf("\nThe multiplication of two matrix is\n");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",c[i][j]);
}
return 0;
}
Check Your Progress 3
Right to left binary exponentiation for a283is as follows: n=283, binary equivalent to
binary string 100011011, s=9 (length of binary string)
result = a (since A[0]=1)
23
Introduction to Algorithm
UNIT 4 SOLVING RECURRENCES
Structure
4.0 Introduction
4.1 Objectives
4.2 Recurrence Relation
4.3 Methods for Solving Recurrence Relation
4.3.1 Substitution method
4.3.2 Recursion Tree Method
4.3.3 Master Method
4.4 Summary
4.5 Solution to check your progress
4.6 Further Reading
4.0 INTRODUCTION
4.1 OBJECTIVES
1
Solving Recurrence
recursively, especially those problems which are solved through Divide and
Conquer technique. In this case, the main problem is divided into smaller sub-
problems which are solved recursively. Quick Sort, Merge Sort, Binary search,
Strassen’s multiplication algorithm are formulated as recursive algorithms .These
problems will be taken up separately in the next block.
Like all recursive functions, a recurrence relation also consists of two steps: (i) one or
more initial conditions and (ii) recursive definition of a problem
Example 1: A Fibonacci sequence 𝑓0, 𝑓1, 𝑓2, … .. can be defined by the recurrence
relation as:
0 𝑖𝑓 𝑛 = 0
𝑓𝑛 = {0 𝑖𝑓 𝑛 = 1
𝑓𝑛−1 + 𝑓𝑛−2 𝑖𝑓 𝑛 ≥ 2
For example 𝒇𝟐 = 𝒇𝟏 + 𝒇𝟎 = 𝟏 + 𝟎 = 𝟏;
𝑓3 = 𝑓2 + 𝑓1 = 1 + 1 = 2 ; 𝑓4 = 𝑓3 + 𝑓2 = 2 + 1 = 3 and so on
Example 2 Find out the value of n! = n (n-1) (n-2)……. (3) (2) (1) for n ≥ 1
1 𝑖𝑓 𝑛 = 1
𝑛! = {
𝑛. (𝑛 − 1)! 𝑖𝑓 𝑛 > 1
int fact(int n)
1: 𝑖𝑓 𝑛 == 0 𝑡ℎ𝑒𝑛
2: 𝑟𝑒𝑡𝑢𝑟𝑛 1
3: 𝑒𝑙𝑠𝑒
4: 𝑟𝑒𝑡𝑢𝑟𝑛 𝑛 ∗ (𝑛 − 1)
5: 𝑒𝑛𝑑𝑖𝑓
Let us try to understand the efficiency of the algorithm in terms of the number of
multiplications operations required for each value of n
Let (𝑛) denoted the number of multiplication required to execute the n!,
2
that is 𝑇(𝑛) denotes the number of times the line 4 is executed in factorial Introduction to Algorithm
algorithm.
We have the initial condition T(0) = 1; since when n = 0, fact simply returns
(i.e. Number of multiplication is0).
1: if(𝑛 == 0)
2: 𝑟𝑒𝑡𝑢𝑟𝑛 1
3: if(𝑛 == 1)
4: 𝑟𝑒𝑡𝑢𝑟𝑛 𝑥
5: 𝒆𝒍𝒔𝒆
7: 𝑒𝑛𝑑𝑖𝑓
The algorithm 3 performs one comparison and one return statement. Therefore,
(0)𝑎𝑛𝑑 (1) = O(1) = 𝑎
When n > 1; the algorithm3 performs one recursive call with input parameter (n – 1)
at line 6, and some constant number of basic operations. Thus we obtain the recurrence
relation as:
(1) = 𝑎 (𝑏𝑎𝑠𝑒 𝑐𝑎𝑠𝑒)
(𝑛) = {
(𝑛 − 1) + 𝑏 (𝑅𝑒𝑐𝑢𝑟𝑠𝑖𝑣𝑒 𝑠𝑡𝑒𝑝)
Example 4: A customer makes an investment of Rs. 5000 at 15 percent annual
compound interest. If 𝑇𝑛 denotes the amount earned at the end of n years, define a
recurrence relation and initial conditions
Ans- At the end of n-1 years, the amount is 𝑇𝑛−1. After one more year , the amount
will be 𝑇𝑛−1 + the interest amount. Therefore
𝑇𝑛 = 𝑇𝑛−1 + (15%)−1=(0.15)𝑇𝑛−1 = (1.15)𝑇𝑛−1 ; n≥ 1
3
Solving Recurrence
To find out the recurrence relation when n=1 ( base value) we have to find the value
of 𝑇0.
Since 𝑇0 refers to the initial amount, 𝑇0 = 5000
With the above definitions we can calculate the value of 𝑇𝑛 for any value of n. For
example:
𝑇3= (1.15)2=(1.15)(1.15)𝑇1 = (1.15)(1.15)(1.15)𝑇0 = (1.15)3(5000)
The above computation can be extended to any arbitrary value of n.
𝑇𝑛 = (1.15)−1
.. ..
= ((1.15)(5000)
Or (𝑛) ≤ 𝑐. 𝑛𝑙𝑜𝑔𝑛
Step2: Now we use mathematical Induction.
Here our guess does not hold for n=1because (1) ≤ 𝑐. 1𝑙𝑜𝑔1
𝑖. 𝑒. (𝑛) ≤ 0 𝑤ℎ𝑖𝑐ℎ 𝑖𝑠 𝑐𝑜𝑛𝑡𝑟𝑎𝑑𝑖𝑐𝑡𝑖𝑜𝑛 𝑤𝑖𝑡ℎ (1) = 1
2
2𝑇 + 2 ≤ 𝑐. 2
2
2(1) + 2 ≤ 𝑐. 2
0 + 2 ≤ 𝑐. 2
This recurrence (1) describe the running time of any divide-and-conquer algorithm.
𝒏
Method (steps) for solving a recurrence (𝒏) = 𝒂 𝑻 ( ) + (𝒏) using recursion
𝒃
tree:
5
Solving Recurrence 𝒏
(b) Now we have to find the value of 𝑻 ( ) by putting (n/b) in place of n in
𝒃
equation (1).That is
From equation (2), now (𝑛⁄𝑏) will be the value of node having a branch (child
𝑛
nodes) each of size T(n/b). Now each 𝑇 ( )in figure-a will be replaced as follows:
𝑏
c) In this way you can expend a tree one more level (i.e. up to (at least) 2 levels).
Step2: (a) Now you have to find per level cost of a tree. Per level cost is the sum of
the cost of each node at that level. For example per level cost at level1 is
𝑛 𝑛 𝑛
( ) + 𝑓 ( ) + ⋯ 𝑓 ( ) (𝑎 𝑡𝑖𝑚𝑒𝑠). This is also called Row-Sum.
𝑏 𝑏 𝑏
(b) Now the total (final) cost of the tree can be obtained by taking the sum of costs of
all these levels.
𝒏
Example1: Solve the recurrence (𝒏) = 𝟐𝑻 ( ) + 𝒏 using recursion tree method.
𝟐
1. To make a recursion tree, you have to write the value of (𝑛) at root node. And
2. The number of child of a Root Node is equal to the value of a. (Here the
value of a = 2).So recursion tree be looks like as:
6
Introduction to Algorithm
𝑛
b) Now we have to find the value of 𝑇 ( ) in figure (a) by putting (n/2) in
2
place of n in equation (1).That is
𝑛
From equation (2), now ( ) will be the value of node having 2 branch (child nodes)
2
𝑛
each of size T(n/2). Now each 𝑇 ( ) in figure-a will be replaced as follows:
2
7
Solving Recurrence
c) In this way, you can extend a tree up to Boundary condition (when problem
size becomes 1). So the final tree will be looks like:
Now we find the per level cost of a tree, Per-level cost is the sum of the costs within
each level (called row sum). Here per level cost is For example: per level cost at depth
2 in figure--c can be obtained as:
Then total cost is the sum of the costs of all levels (called column sum), which gives
the solution of a given Recurrence. The height of the tree is
To find the sum of this series you have to find the total number of terms in this series.
To find a total number of terms, you have to find a height of a tree.
Height of tree can be obtained as follow (see recursion tree of figure c): you start a
𝑛 𝑛
problem of size n, then problem size reduces to( ), then( 2), and so on till boundary
2 2
condition (problem size 1) is not reached. That is
Solution: We always omit floor & ceiling function while solving recurrence.
Thus given recurrence can be written as:
9
Solving Recurrence 𝑛 𝑛 𝑛
𝑛 → ( ) → ( 2) → ⋯ … … … → ( 𝑘)
3 3 3
𝑛 + 𝑛 + ⋯ … … … + (𝑙𝑜𝑔3𝑛 𝑡𝑖𝑚𝑒𝑠)
𝑛𝑙𝑜𝑔2𝑛
⟹ 𝑛𝑙𝑜𝑔 𝑛 = = 𝛺(𝑛𝑙𝑜𝑔 𝑛) − − − − − (∗∗)
3 2
𝑙𝑜𝑔23
T(𝑛) = Θ (𝑛𝑙𝑜𝑔2𝑛)
Remark: If
𝒇(𝒏) = 𝑶(𝒈(𝒏))𝒂𝒏𝒅 𝒇(𝒏) = 𝜴(𝒈(𝒏))𝒕𝒉𝒆𝒏 𝒇𝑰𝒏) = 𝜣(𝒈(𝒏))
Solution:
Figure-a to figure-c shows a step-by-step derivation of a recursion tree for the given
recurrence T(𝑛) = 2𝑇 (𝑛 − 1) + 1
10
⟹ 𝑛 → (𝑛 − 1) → (𝑛 − 2) → ⋯ … … . . → 2 → 1 Introduction to Algorithm
11
Solving Recurrence
𝑛 𝑛
𝑟𝑒𝑡𝑢𝑟𝑛 𝑥 ∗ 𝐹𝑎𝑠𝑡_𝑝𝑜𝑤𝑒𝑟 (𝑥, ) ∗ 𝐹𝑎𝑠𝑡_𝑝𝑜𝑤𝑒𝑟 (𝑥, )
2 2
}
b)
Fibnacci (n)
{ if (n = = 0)
return 0;
if (n = = 1)
return 1;
𝑛 𝑛 𝑛
𝑏. 𝑇(𝑛) = 𝑇 ( ) + 𝑇 ( ) + 𝑇 ( ) + 𝑛
2 4 8
12
4.3.3 MASTERMETHOD Introduction to Algorithm
asymptotically positive function. This recurrence gives us the running time of an algorithm
𝒏
that divides a problem of size n into a subproblems of size .
𝒃
𝒏
The a subproblems are solved recursively, each in time T 𝒃
. The cost of dividing the
problem and combining the results of the subproblems is described by the function f(n) This
recurrence is technically correct only
𝒏 𝒏 𝒏
when 𝒃
is an integer, so the assumption will be made that 𝒃
is either 𝒃
𝒏
or 𝒃
since such a replacement does not affect the asymptotic behavior of the recurrence.
The value of a and b is a positive integer since one can have only a whole number of
subproblems.
The Master Method requires memorization of the following 3 cases; then the solution
of many recurrences can be determined quite easily, often without using pencil &
paper.
𝑛
Case3: If (𝑛) = (𝑛𝑙𝑜𝑔𝑏𝑎+∈ )for some ∈> 0 , and if 𝑎𝑓 ( ) ≤ 𝑐𝑓(𝑛) for
𝑏
Remark: To apply Master method you always compare 𝑛𝑙𝑜𝑔𝑏𝑎 and f(𝑛)The larger of
the two functions determines solution to the recurrence problems. If the growth rate
of these two functions then it belongs to case 2.In this case we multiply by a
logarithmic factor to get the run time solution (T(n)) of recurrence relation.
13
Solving Recurrence
If f(𝑛) is polynomially smaller than 𝑛𝑙𝑜𝑔𝑏 (by a factor of 𝑛∈then case 1 will be
applicable to find 𝑇(𝑛).
If f(𝑛) is polynomially larger than 𝑛𝑙𝑜𝑔𝑏𝑎 (by a factor of1⁄𝑛∈ then
𝑇(𝑛) = 𝜃(𝑓(𝑛) 𝑤ℎ𝑖𝑐ℎ 𝑖𝑠 𝑖𝑛 𝒄𝒂𝒔𝒆 𝟑.
Q.1: Write the first two cases (Case 1 and Case 2) of Master method to solve a
recurrence relation of the form:
𝑛
𝑇(𝑛) = 𝑎𝑇 ( ) + 𝑓(𝑛)
𝑏
Q.2: Use Master Theorem to give the tight asymptotic bounds of the following
recurrences:
14
Introduction to Algorithm
4.4 SUMMARY
When an algorithm contains a recursive call to itself, its running time can often be
described by a recurrence equation which describes a function in terms of its value on
smaller inputs.
In master method you have to always compare the value of 𝑓(𝑛) with 𝑛
to decide which case is applicable.
4.5 SOLUTIONS/ANSWERS
Q 1: a)
At every step the problem size reduces to half the size. When the power is an odd
number, the additional multiplication is involved. To find a time complexity of this
algorithm, let us consider the worst case, that is we assume that at every step additional
multiplication is needed. Thus total number of operations T(n) will reduce to number of
operations for n/2, that is T(n/2) with three additional arithmetic operations(In odd power
case: 2 multiplication and one division). Now we can write:
(𝑛) = 1 𝑖𝑓 𝑛 = 0 𝑜𝑟 1
Instead of writing exact number of operations needed by the algorithm, we can use some
constants. The reason for writing this constant is that we are always interested to find
“asymptotic complexity” instead of finding exact number of operations needed by
algorithm, and also it would not affect our complexity also.
15
Solving Recurrence
Q2 (a) The recursion tree for the given recurrence relation is:
Figure a
Figure b
……. n
………n
…….. n
……………… ………………..
𝒏
Figure c: A Recurrence Tree for 𝑻(𝒏) = 𝟒𝑻 𝟐
+𝒏
16
Introduction to Algorithm
(2𝑙𝑜𝑔 − 1)
= 𝑛∴ (𝑛) = (𝑛2) = 𝑛 − 𝑛 = (𝑛 )
2−1
Q2(d)
Case1: If for some (𝑛) = (𝑛𝑙𝑜𝑔𝑏𝑎−∈) for some ∈ > 0 ,then 𝑇(𝑛) = Θ(𝑛𝑙𝑜𝑔𝑏𝑎)
Solution2:
a) In a recurrence (𝑛) = 4𝑇 + 𝑛, 𝑎 = 4, 𝑏 = 2,
(𝑛) = 𝑛 𝑙𝑜𝑔𝑏𝑎
= 𝑛2. 𝑁𝑜𝑤 𝑐𝑜𝑚𝑝𝑎𝑟𝑒 𝑓(𝑛)𝑤𝑖𝑡ℎ 𝑛𝑙𝑜𝑔𝑏𝑎 .
𝑆𝑖𝑛𝑐𝑒 𝑓(𝑛) = 𝑂 (𝑛𝑙𝑜𝑔𝑏𝑎−∈).
𝑤ℎ𝑒𝑟𝑒 ∈= 1. 𝐵𝑦 𝑀𝑎𝑠𝑡𝑒𝑟 𝑇ℎ𝑒𝑜𝑟𝑒𝑚 𝑐𝑎𝑠𝑒 1 𝑤𝑒 𝑔𝑒𝑡 (𝑛) = Θ (n2).
17