unit-1(Module-1)
unit-1(Module-1)
1. Algorithms
An algorithm is a type of effective method in which a definite list of well-defined
instructions for completing a task; that given an initial state, will proceed through a well-
defined series of successive states, eventually terminating in an end-state. The concept of
an algorithm originated as a means of recording procedures for solving mathematical
problems such as finding the common divisor of two numbers or multiplying two
numbers.
Algorithms are named for the 9th century Persian mathematician Al-Khowarizmi. He
wrote a treatise in Arabic in 825 AD, On Calculation with Hindu Numerals. It was
translated into Latin in the 12th century as Algoritmi de numero Indorum, which title was
likely intended to mean "[Book by] Algoritmus on the numbers of the Indians", where
"Algoritmi" was the translator's rendition of the author's name in the genitive case; but
people misunderstanding the title treated Algoritmi as a Latin plural and this led to the
word "algorithm" (Latin algorismus) coming to mean "calculation method".
programming languages, the control component is fixed and algorithms are specified
by supplying only the logic component. The appeal of this approach is the elegant
semantics: a change in the axioms has a well-defined change in the algorithm.
Serial or parallel or distributed: Algorithms are usually discussed with the
assumption that computers execute one instruction of an algorithm at a time. Those
computers are sometimes called serial computers. An algorithm designed for such an
environment is called a serial algorithm, as opposed to parallel algorithms or
distributed algorithms. Parallel algorithms take advantage of computer architectures
where several processors can work on a problem at the same time, whereas distributed
algorithms utilise multiple machines connected with a network. Parallel or distributed
algorithms divide the problem into more symmetrical or asymmetrical subproblems
and collect the results back together. The resource consumption in such algorithms is
not only processor cycles on each processor but also the communication overhead
between the processors. Sorting algorithms can be parallelized efficiently, but their
communication overhead is expensive. Iterative algorithms are generally
parallelizable. Some problems have no parallel algorithms, and are called inherently
serial problems.
Deterministic or non-deterministic: Deterministic algorithms solve the problem with
exact decision at every step of the algorithm whereas non-deterministic algorithm
solves problems via guessing although typical guesses are made more accurate
through the use of heuristics.
Exact or approximate: While many algorithms reach an exact solution,
approximation algorithms seek an approximation that is close to the true solution.
Approximation may use either a deterministic or a random strategy. Such algorithms
have practical value for many hard problems.
A recursive algorithm is an algorithm which calls itself with "smaller (or simpler)"
input values, and which obtains the result for the current input by applying simple
operations to the returned value for the smaller (or simpler) input. More generally if a
problem can be solved utilizing solutions to smaller versions of the same problem, and
the smaller versions reduce to easily solvable cases, then one can use a recursive
algorithm to solve that problem. For example, the elements of a recursively defined set, or
the value of a recursively defined function can be obtained by a recursive algorithm.
Recursive computer programs require more memory and computation compared with
iterative algorithms, but they are simpler and for many cases a natural way of thinking
about the problem.
In other words,
factorial(0)=> 1
factorial(3)
3 * factorial(2)
3 * 2 * factorial(1)
3 * 2 * 1 * factorial(0)
3*2*1*1
=> 6
This corresponds very closely to what actually happens on the execution stack in the
computer's memory.
1. Instruction Space
Space needed to store the compiled version of program. It depends on
i. Compiler used
ii. Options specified at the time of compilation
e.g., whether optimization specified, Is there any overlay option etc.
iii. Target computer
e.g., For performing floating point arithmetic, if hardware present or not.
2. Data Space
Space needed to store constant and variable values. It has two components:
i. Space for constants:
e.g., value ‘3’ in program 1.1
Space for simple variables:
e.g., variables a,b,c in program 1.1
Program 1.1
int add (int a, int b, int c)
{
return (a+b+c)/3;
}
ii. Space for component variables like arrays, structures, dynamically allocated
memory.
e.g., variables a in program 1.2
Program 1.2
int Radd (int a[], int n)
1 {
2 If (n>0)
3 return Radd (a, n-1) + a[n-1];
4 else
5 return 0;
6 }
Example 1.1
Refer Program 1.1
One word for variables a,b,c. No instance characteristics. Hence Sp(TC) = 0
Example 1.2
Program 1.3
int Aadd (int *a, int n)
1 {
2 int s=0;
3 for (i=0; i<n; i++)
4 s+ = a[i];
5 return s;
6 }
One word for variables n and i. Space for a[] is address of a[0]. Hence it requires one
word. No instance characteristics. Hence Sp(TC) = 0
Example 1.3
Refer Program 1.2
Instance characteristics depend on values of n. Recursive stack space includes space
for formal parameters, local variables and return address. So one word each for a[],n,
return address and return variables. Hence for each pass it needs 4 words. Total recursive
stack space needed is 4(n).
Hence Sp(TC) = 4(n).
Time complexity of an algorithm is the amount of time needed by the program for its
completion. Time taken is the sum of the compile time and the execution time. Compile
time does not depend on instantaneous characteristics. Hence we can ignore it.
1. Comments:
No executables, hence step count = 0
2. Declarative Statements:
Define or characterize variables and constants like (int , long, enum, …)
Statement enabling data types (class, struct, union, template)
Determine access statements ( public, private, protected, friend )
Character functions ( void, virtual )
All the above are non executables, hence step count = 0
4. Iterative Statements:
While <expr> do
Do .. While <expr>
Step count = Number of step count assignable to <expr>
5. Switch Statements:
Switch (<expr>) {
Case cond1 : <statement1>
Case cond2 : <statement2>
.
.
Default : <statement>
}
6. If-else Statements:
If (<expr>) <statement1>;
Else <statement2>;
Step count of If and Else is the cost of <expr>.
7. Function invocation:
All function invocation has Step count = 1, unless it has parameters passed as called
by value which depend s on instance characteristics. If so, Step count is the sum of the
size of these values.
If function being invoked is recursive, consider the local variables also.
9. Function Statements:
Step count = 0, cost is already assigned to invoking statements.
Example 1.4
Refer Program 1.2
Introducing a counter for each executable line we can rewrite the program as
Case 2: n>0
2 + tRadd (n-1)
= 2 + 2 + tRadd (n-2)
= 2 * 2 + tRadd (n-2)
.
.
= 2n + tRadd (0)
= 2n + 2
Example 1.5
Program 1.4
int Madd (int a[][], int b[][], int c[][], int n)
1 {
2 For (int i=0; i<m; i++)
3 For (int j=0; j<n; j++)
4 c[i][j] = a[i][j] + b[i][j];
5 }
Introducing a counter for each executable line we can rewrite the program as
int Madd (int a[][], int b[][], int c[][], int n)
{
For (int i=0; i<m; i++)
{
count++ //for i
For (int j=0; j<n; j++)
{
count++ //for j
c[i][j] = a[i][j] + b[i][j];
count++ //for assignment
}
count++ //for last j
}
count++ //for last i
}
Step count is 2mn + 2m +1.
Step count does not reflect the complexity of statement. It is reflected in step per
execution (s/e).
For example, consider two programs with complexities c1n2 + c2n and c3n
respectively. For small values of n, complexity depend upon values of c1, c2 and c3. But
there will also be an n beyond which complexity of c3n is better than that of c1n2 +
c2n.This value of n is called break-even point. If this point is zero, c3n is always faster (or
at least as fast). Common asymptotic functions are given below.
Function Name
1 Constant
log n Logarithmic
n Linear
n log n n log n
n2 Quadratic
n3 Cubic
2n Exponential
n! Factorial
O(g(n)) = { f(n) : there exist positive constants c and n0 such that 0 ≤ f(n) ≤ cg(n) for all n
≥ n0 }
It is the upper bound of any function. Hence it denotes the worse case complexity of any
algorithm. We can represent it graphically as
Fig 1.1
Linear Functions
Example 1.6
f(n) = 3n + 2
When n ≥ 2, 3n + 2 ≤ 3n + n = 4n
Hence f(n) = O(n), here c = 4 and n0 = 2
When n ≥ 1, 3n + 2 ≤ 3n + 2n = 5n
Hence f(n) = O(n), here c = 5 and n0 = 1
Hence we can have different c,n0 pairs satisfying for a given function.
Example 1.7
f(n) = 3n + 3
When n ≥ 3, 3n + 3 ≤ 3n + n = 4n
Hence f(n) = O(n), here c = 4 and n0 = 3
Example 1.8
f(n) = 100n + 6
When n ≥ 6, 100n + 6 ≤ 100n + n = 101n
Hence f(n) = O(n), here c = 101 and n0 = 6
Quadratic Functions
Example 1.9
f(n) = 10n2 + 4n + 2
When n ≥ 2, 10n2 + 4n + 2 ≤ 10n2 + 5n
When n ≥ 5, 5n ≤ n2, 10n2 + 4n + 2 ≤ 10n2 + n2 = 11n2
Hence f(n) = O(n2), here c = 11 and n0 = 5
Example 1.10
f(n) = 1000n2 + 100n - 6
Exponential Functions
Example 1.11
f(n) = 6*2n + n2
When n ≥ 4, n2 ≤ 2n
So f(n) ≤ 6*2n + 2n = 7*2n
Hence f(n) = O(2n), here c = 7 and n0 = 4
Constant Functions
Example 1.12
f(n) = 10
f(n) = O(1), because f(n) ≤ 10*1
Fig 1.2
Example 1.13
f(n) = 3n + 2
3n + 2 > 3n for all n.
Hence f(n) = Ω(n)
Similarly we can solve all the examples specified under Big ‘Oh’.
Fig 1.3
Example 1.14
f(n) = 3n + 2
f(n) = Θ(n) because f(n) = O(n) , n ≥ 2.
It defines the asymptotic tight upper bound. Main difference with Big Oh is that Big Oh
defines for some constants c by Little Oh defines for all constants.
(1) if n = 1
T(n)
2T(n/2) + (n) if n > 1
Steps
Guess the form of the solution
Use mathematical induction to find constants or show that they can be found and
to prove that the answer is correct
Example 1.15
Find the upper bound for the recurrence relation
T(n) = 2 T( n/2 ) + n
Example 1.16
Find the worse case complexity of Binary Search
T(n) = c + T(n/2)
Example 1.17
T(n) = T(n-1) + n
Example 1.17
T(n) = 2T(n/2) + n
• Guess: T(n) = O(nlgn)
– Induction goal: T(n) ≤ cn lgn, for some c and n ≥ n0
– Induction hypothesis: T(n/2) ≤ cn/2 lg(n/2)
• Proof of induction goal:
T(n) = 2T(n/2) + n ≤ 2c (n/2)lg(n/2) + n
= cn lgn – cn + n ≤ cn lgn
if: - cn + n ≤ 0 c ≥ 1
Steps
Convert the recurrence into a tree.
Each node represents the cost of a single sub problem somewhere in the set of
recursive function invocations
Sum the costs within each level of the tree to obtain a set of per-level costs
Sum all the per-level costs to determine the total cost of all levels of the recursion
Example 1.18
T(n) = 3T(n/4) + (n2)
T(n) = 3T(n/4) + cn2
3 2 3 3
T (n) cn 2 cn ( ) 2 cn 2 ... ( ) log 4 n 1 cn 2 (n log 4 3 )
16 16 16
log 4 n 1
3
i 0
( )i cn 2 (n log 4 3 )
16
3 i 2
( ) cn (n log 4 3 )
i 0 16
1 16 2
cn 2 (n log 4 3 ) cn (n log 4 3 )
3 13
1
16
O(n 2 )
T (n) 3T ( n / 4) cn 2
3d n / 4 cn 2
2
3d (n / 4) 2 cn 2
3 2
dn cn 2
16
dn 2
Example 1.19
W(n) = 2W(n/2) + (n2)
Example 1.20
W(n) = W(n/3) + W(2n/3) + O(n)
• The longest path from the root to a leaf is: n (2/3)n (2/3)2 n … 1
• Subproblem size hits 1 when 1 = (2/3)in i=log3/2n
• Cost of the problem at level i = n
• Total cost:
log 3 / 2 n log 3 / 2 n
lg n 1
n n ... n n
i 0
1 n log
i 0
3/ 2 nn
lg 3 / 2 lg 3 / 2
n lg n
W(n) = O(nlgn)
Example 1.21
T(n) = T(n/4) + T(n/2) + n2
The master method applies to recurrences of the form T(n) = a T(n/b) + f (n) ,
where a 1, b > 1, and f is asymptotically positive.
Describe the running time of an algorithm that divides a problem of size n into a
sub problems, each of size n/b
Case 1
Compare f (n) with nlogba
If f (n) = O(nlogba – e) for some constant e > 0.
i.e., f (n) grows polynomially slower than nlogba
i.e., f(n) is asymptotically smaller by an ne factor.
Then Solution: T(n) = Θ(nlogba) .
Case 2
Compare f (n) with nlogba
If f (n) = Θ (nlogba)
i.e., f (n) and nlogba grow at similar rates.
Then Solution: T(n) = Θ(nlogba lgn) .
Case 3
Compare f (n) with nlogba
If f (n) = Ω(nlogba+e) for some constant e > 0
i.e., f (n) grows polynomially faster than nlogba
i.e., f(n) is asymptotically larger by an ne factor.
Then Solution: T(n) = Θ(f(n)) .
Example 1.22
T(n)=9T(n/3) + n
a=9, b=3, f(n) = n
CASE 1: n log b a n log 3 9 (n 2 ), f (n) O(n log 3 91 )
T(n) = (n2)
Example 1.23
T(n) = 4T(n/2) + n
a = 4, b = 2 nlogba = n2; f (n) = n.
CASE 1: f (n) = O(n2 – e) for e = 1.
T(n) = Θ(n2).
Example 1.24
T(n) = T(2n/3) + 1
a=1, b=3/2,logf(n)=1
Case 2: n
ba
n log 3 / 2 1 1, f (n) 1 (1)
T(n) = (lg n)
Example 1.25
T(n) = 4T(n/2) + n2
a = 4, b = 2 nlogba = n2; f (n) = n2.
CASE 2: f (n) = Q(n2lg0n), that is, k = 0.
Example 1.27
T(n) = 4T(n/2) + n3
a = 4, b = 2 nlogba = n2; f (n) = n3.
CASE 3: f (n) = Ω(n2 + e) for e = 1 and 4(cn/2)3 £ cn3 (reg. cond.) for c = 1/2.
T(n) = Θ(n3).
Set Representation:
The set will be represented as the tree structure where all children will store the address
of parent / root node. The root node will store null at the place of parent address. In the given
set of elements any element can be selected as the root node, generally we select the first node
as the root node.
Example:
S1={1,7,8,9} S2={2,5,10} s3={3,4,6}
Disjoint Union:
To perform disjoint set union between two sets Si and Sj can take any one root and
make it sub-tree of the other. Consider the above example sets S1 and S2 then the union of S1
and S2 can be represented as any one of the following.
Find:
To perform find operation, along with the tree structure we need to maintain the name
of each set. So, we require one more data structure to store the set names. The data structure
contains two fields. One is the set name and the other one is the pointer to root.