FDS U1 Technical
FDS U1 Technical
Introduction to Algorithm
1 and Data Structures
Syllabus
Introduction : From Problem to Program (Problem, Solution, Algorithm, Data Structure and
Program). Data Structures : Data, Information, Knowledge, and Data structure, Abstract Data Types
(ADT), Data Structure Classification (Linear and Non-linear, Static and Dynamic, Persistent and
Ephemeral data structures).
Algorithms : Problem Solving, Introduction to algorithm, Characteristics of algorithm, Algorithm
design tools : Pseudo-code and flowchart. Complexity of algorithm : Space complexity, Time
complexity, Asymptotic notation- Big-O, Theta and Omega, Finding complexity using step count
method, Analysis of programming constructs-Linear, Quadratic, Cubic, Logarithmic.
Algorithmic Strategies : Introduction to algorithm design strategies - Divide and Conquer, and
Greedy strategy.
Contents
1.1 From Problem to Data Structure (Problem, Logic, Algorithm, and Data Structure)
1.2 Data Structures : Data, Information, Knowledge, and Data Structure
1.3 Abstract Data Types (ADT). . . . . . . . . . . . . . . Dec.-10, 11,
. . . . . . . . . . . . . . . . . May-10, 11, 12, 13, 19, · · · · · · Marks 6
1.4 Data Structure Classification . . . . . . . . . . . . . May-17, Dec.-18, 19, · · · · · · · · Marks 4
1.5 Problem Solving . . . . . . . . . . . . . . . . . Dec.-09, 10, May-10, 11, · · · · Marks 12
1.6 Difficulties in Problem Solving . . . . . . . . . . . . Dec.-10, May-16, · · · · · · · · · · · Marks 4
1.7 Introduction to Algorithm. . . . . . . . . . . . . . . . . Dec.-16, May-18, 19, · · · · · · · · Marks 4
1.8 Algorithm Design Tools . . . . . . . . . . . . . . . . . May-10, 11, Dec.-10, · · · · · · · · Marks 8
1.9 Step Count Method
1.10 Complexity of Algorithm . . . . . . . . . . . . . . . . . Dec.-09, 10, 11, 19,
. . . . . . . . . . . . . . . . . May-12, 13, · · · · · · · · · · · · · · · Marks 8
1.11 Asymptotic Notations . . . . . . . . . . . . . . . . . Dec.-09, 10, 11, 16, 17, 19,
. . . . . . . . . . . . . . . . . May-10, 12, 13, 18, 19, · · · · · · Marks 8
1.12 Analysis of Programming Constructs . . . . . . . May-10, 13, 14, Dec.-11, 13, · · Marks 8
1.13 Recurrence Relation . . . . . . . . . . . . . . . . . Dec.-18, · · · · · · · · · · · · · · · · · · Marks 2
1.14 Solving Recurrence Relation
1.15 Best, Worst and Average Case Analysis
1.16 Introduction to Algorithm Design Strategies . . May-17, 18, Dec.-17, 19, · · · · · Marks 6
(1 - 1)
Fundamentals of Data Structures 1-2 Introduction to Algorithm and Data Structures
0 1 2 3 4
10 20 30 40 50
Any element in above array can be referred by an index. For instance the element 40
can be accessed as array[3].
AbstractDataType Set {
Instances : Set is a collection of integer type of elements.
Preconditions : none
Operations :
1. Store ( ) : This operation is for storing the integer element in a set.
2. Retrieve ( ) : This operation is for retrieving the desired element from the given
set.
3. Display ( ) : This operation is for displaying the contents of set.
}
There is a specific method using which an ADT can be written. We begin with
keyword AbstractDataType which is then followed by name of the data structure for
which we want to write an ADT. In above given example we have taken Set data
structure.
· Then inside a pair of curly brackets ADT must be written.
· We must first write instances in which the basic idea about the corresponding
data structure must be given. Generally in this section definition of corresponding
data structure is given.
· Using Preconditions or Postconditions we can mention specific conditions that
must be satisfied before or after execution of corresponding function.
· Then a listing of all the required operations must be given. In this section, we
must specify the purpose of the function. We can also specify the data types of
these functions.
Review Questions
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1-5 Introduction to Algorithm and Data Structures
3. Explain following terminologies : i) Data type ii) Data structure iii) Abstract data type.
SPPU : May-13, Marks 6
The data structures can be divided into two basic types primitive data structure and
non primitive data structure. The Fig. 1.4.1. shows various types of data structures.
Data structure
The dynamic data structure is a data structure in which one can allocate the memory
as per his requirement. If one does not want to use some block of memory, he can
deallocate it.
For example (Dynamic Data Structure (Dynamic)) :
Linked list, the linked list is a collection of many nodes. Each node consists of data
and pointer to next node. In linked list user can create as much nodes (memory) as he
wants, he can dellocate the memory which cannot be utilized further.
The advantage of dynamic data structure over the static data structure is that there
is no wastage of memory.
30
State 1 : 20 20
10 10 10
stack stack stack
(a) (b) (c)
30
we have pushed 10, 20 and 30 in the
State 2 : 20 stack
10
stack
The ephemeral data structures are the data structures in which we cannot retain its
previous state.
For example Queues
State 1 : In queues elements are inserted by one end and deleted by other end. Let us
insert 10, 20, 30 in the queue.
10 10 20 10 20 30
State 2 : Now if we delete the element, we can delete it only by other end. That means
10 can be deleted. And queue will be -
20 30
Now this state is not matching with any of the previous states. That means we can
not retain the previous state of the data structure even after performing certain
operations. Such a data structure is called ephemeral data structure.
Review Questions
1. Differentiate between linear and non linear data structure with example.
SPPU : May-17, Marks 3
2. Explain static and dynamic data structures with examples SPPU : Dec.-18, Marks 4
3. Write short note on Linear and Non-Linear data structure with example
SPPU : Dec.-19, Marks 4
Problem solving is based on the decisions that are taken. Following are the six steps
of problem solving -
1. Identify the problem : Identifying the problem is the first step in solving the
problem. Problem identification is very essential before solving any problem.
2. Understand the problem : Before solving any problem it is important to
understand it. There are three aspects based on which the problem can be
understood.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1-8 Introduction to Algorithm and Data Structures
Step 2 : Understand the problem : Here the age of the person must be known so that
the charge for the ticket can be calculated.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1-9 Introduction to Algorithm and Data Structures
Step 4 : Select the best way to solve the problem : The only way to solve this problem
is to calculate ticket charge based on the age of the person.
Review Questions
1. State a reason why each of the six problem solving steps is important in developing the best
solution for a problem. Give one reason for each step. SPPU : May-10, Marks 8
2. Consider any one problem and solve that problem using six steps of problem solving. Explain
each step in detail. SPPU : Dec.-10, Marks 8
3. Describe the six steps in problem solving with example. SPPU : May-11, Marks 8
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 10 Introduction to Algorithm and Data Structures
· When solving the problems on computer then writing the instructions for the
computer is most crucial task. With lack of knowledgebase one can not write the
proper instruction set for the computers.
Review Questions
1. State and explain any four difficulties with problem solving SPPU : Dec.-10, Marks 4
2. What are the difficulties in problem solving ? Explain any four steps in problem solving with
suitable example. SPPU : May-16, Marks 4
Example : Let us take a very simple example of an algorithm which adds the two
numbers and store the result in a third variable.
Step 1 : Start.
Step 2 : Read the first number is variable 'a'
Step 3 : Read the second number in variable 'b'
Step 4 : Perform the addition of both the numbers i.e. and store the result in variable 'c'.
Step 5 : Print the value of 'c' as a result of addition.
Step 6 : Stop.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 11 Introduction to Algorithm and Data Structures
Review Questions
1. Define algorithm and its characteristics. SPPU : Dec.-16, Marks 4, May-19, Marks 2
2. Define and explain following terms – (i) Data (ii) Data structure (iii) Algorithm.
SPPU : May-18, Marks 3
Algorithm
Flow chart
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 12 Introduction to Algorithm and Data Structures
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 13 Introduction to Algorithm and Data Structures
:
:
statement n
}
While the condition is true the block enclosed with { } gets executed otherwise
statement after } will be executed.
13. The general form for writing for loop is :
for variable ¬ value1 to valuen do
{
statement 1
statement 2
:
:
statement n
}
Here value1 is initialization condition and valuen is a terminating condition.
Sometime a keyword step is used to denote increament or decreament the value of
variable for example
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 14 Introduction to Algorithm and Data Structures
Function sum(a,b:integer):integer
{
//body of function
//return statement
}
Procedure sum(a,b:integer):integer
{
//body of procedure
}
The difference between function sub-algorithm and procedure sub-algorithm is that,
the function can return only one value where as the procedure can return more than one
value.
Solution :
Solution :
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 15 Introduction to Algorithm and Data Structures
Solution :
Solution :
Solution :
Algorithm Mul(A,B,n)
//Problem Description:This algorithm is for computing
//multiplication of two matrices
//Input:The two matrices A,B and order of them as n
//Output:The multiplication result will be in matrix C
for i ¬ 1 to n do
for j ¬ 1 to n do
C[i,j] ¬ 0
for k ¬ 1 to n do
C[i,j] ¬ C[i,j]+A[i,k]B[k,j]
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 16 Introduction to Algorithm and Data Structures
1.8.2 Flowchart
I/O
Decision
Process Module
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 17 Introduction to Algorithm and Data Structures
Example 1.8.6 What do you mean by flow chart ? Give the meaning of each symbol used in
flowchart. Draw flowchart to compute the sum of elements from a given integer array
SPPU : May-10, Marks 8
Solution : Refer section 1.8.2 for flowchart and symbols used in it.
Start
Read array
elements
Sum = 0
i=
1 1 n
Display Sum
Stop
Fig. 1.8.2
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 18 Introduction to Algorithm and Data Structures
Example 1.8.7 Design and explain an algorithm to find the sum of the digits of an integer
number. SPPU : Dec.-10, Marks 6
Solution :
Read N
Remainder=0
Sum=0
Repeat
Remainder=N mod 10
Sum=Sum+remainder
N=N/10
Until N<0
Display Sum
End
Example 1.8.8 What is a difference between flowchart and algorithm ? Convert the algorithm
for computing factorial of given number into flowchart. SPPU : May-11, Marks 8
Solution : Algorithm is a set of instructions written in natural language or pseudo code
and flowchart is a graphical representation of an algorithm.
Read N
Set i and F to 1
While i<=N
F=F * i
Increase the value of i by 1
Display F
End
Start
Read the
number 'n'
fact = 1
i=
1 1 n
fact = fact i
Stop
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 19 Introduction to Algorithm and Data Structures
1.10 Complexity of Algorithm SPPU : Dec.-09, 10, 11, 19, May-12, 13, Marks 8
S(p) = C + Sp
where C is a constant i.e. fixed part and it denotes the space of inputs and outputs.
This space is an amount of space taken by instruction, variables and identifiers. And Sp
is a space dependent upon instance characteristics. This is a variable part whose space
requirement depends on particular problem instance.
There are two types of components that contribute to the space complexity - Fixed
part and variable part.
The fixed part includes space for
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 20 Introduction to Algorithm and Data Structures
Example 1.10.1 Compute the space needed by the following algorithms justify your answer.
Algorithm Sum(a,n)
{
s : = 0.0 ;
For i : = 1 to n do
s : = s + a[i] ;
return s
}
In the given code we require space for
s:=0 ¬ O(1)
For i : = 1 to n ¬ O(n)
s : = s + a[i] ; ¬ O(n)
returns ; ¬ O(1)
Hence the space complexity of given algorithm can be denoted in terms of big-oh
notation. It is O(n). We will discuss big oh notation concept in section 1.11.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 21 Introduction to Algorithm and Data Structures
2. What do you mean by frequency count and its importance in analysis of an algorithm
SPPU : Dec.-09,10, May-12,13, Marks 6
To choose the best algorithm, we need to check efficiency of each algorithm. The
efficiency can be measured by computing time complexity of each algorithm. Asymptotic
notation is a shorthand way to represent the time complexity.
Using asymptotic notations we can give time complexity as “fastest possible”,
“slowest possible” or “average time”.
Various notations such as W, Q and O used are called asymptotic notations.
f(n) £ c*g(n)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 22 Introduction to Algorithm and Data Structures
then f(n) is big oh of g(n). It is also denoted as f(n) Î O (g(n)). In other words f(n) is
less than g(n) if g(n) is multiple of some constant c.
c * g(n)
f(n)
n0 n
f(n) Î O(g(n))
Fig. 1.11.1 Big oh notation
= (1) 2
g(n) = 1
i.e. f(n) > g(n)
If n = 2 then,
f(n) = 2(2) + 2
= 6
g(n) = ( 2) 2
g(n) = 4
i.e. f(n) > g(n)
If n = 3 then,
f(n) = 2(3) + 2
= 8
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 23 Introduction to Algorithm and Data Structures
g(n) = ( 3) 2
g(n) = 9
i.e. f(n) < g(n) is true.
Hence we can conclude that for n > 2, we obtain
f(n) < g(n)
Definition
A function f(n) is said to f(n)
be in W (g(n)) if f(n) is
bounded below by some c * g(n)
positive constant multiple of
g(n) such that
f(n) ³ c * g(n)
For all n ³ n 0
It is denoted as f(n) Î W
(g(n)). Following graph n0 n
illustrates the curve for W
notation. Fig. 1.11.2 Omega notation f(n) Î W (g(n))
Example :
Consider f(n) = 2n 2 + 5 and g(n) = 7n
Then if n = 0
f(n) = 2 ( 0) 2 + 5
= 5
g(n) = 7 (0)
= 0 i.e. f(n) > g(n)
But if n = 1
f(n) = 2 (1) 2 + 5
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 24 Introduction to Algorithm and Data Structures
= 7
g(n) = 7(1)
7 i.e. f(n) = g(n)
If n = 3 then,
f(n) = 2 ( 3) 2 + 5
= 18 + 5
= 23
g(n) = 7(3)
= 21
i.e. f(n) > g(n)
2n 2 + 5 Î W (n)
Similarly any
n 3 Î W (n) 2
1.11.3 Q Notation
The theta notation is denoted by Q. By this method the running time is between
upper bound and lower bound.
Definition
Let f(n) and g(n) be two
c2 * g(n)
non negative functions. There f(n)
are two positive constants
namely c 1 and c 2 such that
c1 * g(n)
c 1 £ g(n) £ c 2 g(n)
where n ³ 2
Fig. 1.11.3 Theta notation f(n) Î Q (g(n))
Similarly f(n) = 2n + 8
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 25 Introduction to Algorithm and Data Structures
g(n) = 7n
i.e. 5n < 2n + 8 < 7n For n ³ 2
Here c1 = 5 and c 2 = 7 with n 0 = 2.
The theta notation is more precise with both big oh and omega notation.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 26 Introduction to Algorithm and Data Structures
2. Polynomials of degree m Î Q (n m ) .
( )
second of O n 2 , then we will usually 2 1 2 4 8 4
prefer the first one. 4 2 8 16 64 16
The reason for this is that as n 8 3 24 64 512 256
increases the time required for the
16 4 64 256 4096 65536
execution of second algorithm will get
far more than the time required for 32 5 160 1024 32768 2147483648
the execution of first.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 27 Introduction to Algorithm and Data Structures
We will study various values for computing function for the constant values. The
graph given below will indicate the rate of growth of common computing time
functions.
Notice how the times O ( n) and O (n log n) grow much more slowly than the others.
For large data sets algorithms with a complexity greater than O (n log n) are often
impractical. The very slow algorithm will be the one having time complexity 2n .
n
2 3
65536 n
32768
16384
2
n
8192
4096
2048
1024
n log2 n
512
256
n
128
64
32
16 log2 n
1 2 4 8 16 32 64 128
Review Questions
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 28 Introduction to Algorithm and Data Structures
3. Explain asymptotic notations Big O, Theta and Omega with one example each.
SPPU : Dec.-16, 17, May-18, Marks 6, Dec.-19, Marks 3
Example 1.12.1 Obtain the frequency count for the following code
Solution :
void fun()
{
int a;
a=0; ………………………………………….1
for(i=0;i<n;i++) …………………………….n+1
{
a = a+i; …………………………………n
}
printf("%d",a); ……………………………….1
}
The frequency count of above code is 2n+3
The for loop in above given fragment of code is executed n times when the condition
is true and one more time when the condition becomes false. Hence for the for loop the
frequency count is n+1. The statement inside the for loop will be executed only when
the condition inside the for loop is true. Therefore this statement will be executed for n
times. The last printf statement will be executed for once.
Example 1.12.2 Obtain the frequency count for the following code
Solution :
void fun(int a[][],int b[][])
{
int c[3][3];
for(i=0;i<m;i++) .....................................m+1
{
for(j=0;j<n;j++) ...................................m(n+1)
{
c[i][j]=a[i][j]+b[i][j]; ...........................m.n
}
}
The frequency count =(m+1)+m(n+1)+mn=2m+2mn+1=2m(1+n)+1
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 29 Introduction to Algorithm and Data Structures
Example 1.12.3 Obtain the frequency count for the following code
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
c[i][j]=0;
for(k=1;k<=n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
} SPPU : May-13, Marks 8; Dec.-13, Marks 3
Solution : After counting the frequency
count, the constant terms can be Statement Frequency Count
neglected and only the order of
for(i=1;i<=n;i++) n+1
magnitude is considered. The time
complexity is denoted in terms of for(j=1;j<=n;j++) n.(n+1)
algorithmic notations. The Big oh
c[i][j]=0; n.(n)
notation is a most commonly used
algorithmic notation. For the above for(k=1;k<=n;k++) n.n(n+1)
frequency count all the constant terms c[i][j]=c[i][j]+a[i][k]*b[k][j n.n.n
are neglected and only the order of ];
magnitude of the polynomial is 3 2
Total 2n +3n +2n+1
considered. Hence the time complexity
for the above code can be O(n3). The
higher order is the polynomial is always considered.
Example 1.12.4 Obtain the frequency count for the following code i=1;
do
{
a++;
if(i==5)
break;
i++;
}while(i<=n)
Solution :
Statement Frequency Count
i=1; 1
a++; 5
if(i==5) 5
break; 1
i++; 5
while(i<=n) 5
Total 22
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 30 Introduction to Algorithm and Data Structures
Example 1.12.5 Obtain the frequency count for the following code
m=n/2;
for(i=0;i+m<m;i++)
{
a++;
k++;
}
Solution :
If we consider only the degree of the polynomial for this code then the time
complexity in terms of Big-oh notation can be specified as O(n/2).
Example 1.12.6 Find the frequency count (F.C.) of the given code :
Explain each step.
double IterPow(double X, int N)
{
double Result = 1;
while (N > 0)
{
Result = Result *X;
N--;
}
return Result;
} SPPU : May-10, Marks 6
Solution :
double Result=1 1
while(N>0) N+1
Result=Result*X N
N-- N
return Result 1
Total 3N+3
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 31 Introduction to Algorithm and Data Structures
Example 1.12.7 What is frequency count of a statement ? Analyze time complexity of the
following code :
i) for(i = 1; i <= n; i++)
for(j = 1; j <= m; j++)
for(k = 1; k <= p; k++)
sum = sum + i;
ii) i = n;
while(i ³ 1)
{i– –;} SPPU : Dec.-11, Marks 6, May-14, Marks 3
Solution : i) ii)
Example 1.12.8 Determine the frequency counts for all the statements in the following
program segment
i=10;
for(i=10;i<=n;i++)
for(j=1;j<i;j++)
x=x+1; SPPU : May-13, Marks 6
Solution : Assume (n–10+2)=m.
Then the total frequency count is - Statement Frequency Count
The outer loop will execute for i=10; 1
m times. The inner loop is
for(i=10;i<=n;i++) m (we assume the count of
dependant upon the outer loop.
execution is m)
Hence it will be (m+1)/2. Hence
overall frequency count is for(j=1;j<i;j++) m((m+1)/2)
(1+m+m )(m(m+1)/2)
2
x=x+1; m(m)
If we consider only the order of
magnitude of this code then overall time complexity in terms of big oh notation is O(n2).
If an algorithm takes time O(logn) then it is faster than any other algorithm, for
larger value of n. Similarly O(nlogn) is better than O(n2). Various computing time can be
O(1), O(logn), O(n),O(nlogn), O(n2), O(n3) and O(2n).
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 32 Introduction to Algorithm and Data Structures
· Definition :
The recurrence equation is an equation that defines a sequences resursively. It is
normally in following form :
Recurrence relation
T(0) = 0 (2)
Initial condition
Review Question
For example -
Consider a recurrence relation
T(n) = T(n – 1) + n
If n = 1 then
T(1) = T(0) + 1
= 0+1 Q Initial condition
\ T(1) = 1 … (1.14.2)
If n = 2, then
T(2) = T(1) + 2
= 1+2 Q equation (1.14.2)
\ T(2) = 3 … (1.14.3)
If n = 3 then
T(3) = T(2) + 3
= 3+3 Q equation (1.14.4)
\ T(3) = 6 … (1.14.5)
But, in practice, it is difficult to guess the pattern from forward substitution. Hence
this method is not very often used.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 34 Introduction to Algorithm and Data Structures
Let
T(n – 2) = T (n – 2 – 1) + (n – 2) … (1.14.9)
Putting equation (1.14.9) in equation (1.14.8) we get.
T(n) = T(n – 3) + (n – 2) + (n – 1) + n
M
= T(n – k) + (n – k + 1) + (n – k + 2) + … + n
if k = n then
T(n) = T(0) + 1 + 2 + … n
T(n) = 0 + 1 + 2 + … + n Q T(0) = 0
n(n + 1) n2 n
T(n) = = +
2 2 2
T(n) = T(n – 1) + 1
By backward substitution,
T(n – 1) = T(n – 2) + 1
\ T(n) = T ( n – 1) + 1
= (T(n – 2) + 1) + 1
T(n) = T(n – 2) + 2
Again T(n – 2) = T(n – 2 – 1) + 1
= T(n – 3) + 1
\ T(n) = T(n – 2) + 2
= (T(n – 3) + 1) + 2
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 35 Introduction to Algorithm and Data Structures
T(n) = T(n – 3) + 3
M
T(n) = T(n – k) + k … (1)
é æ n ö n2 ù
= 4 ê4 × T ç ÷ + + n2
è 2ø 2ú
ë 3 3 û
æ n ö n2
= 4 2T ç ÷ + 4 × + n2
è 32 ø 32
æ n ö 13n 2
= 4 2T ç ÷ +
è 32 ø 32
2
n 13n 2 n n n
= 16 × T æç ö÷ + Q T æç ö÷ = 4T æç ö÷ + æç ö÷
è 9ø 9 è 9ø è 27 ø è 9 ø
é n n 2 ù 13n 2 n n n2
= 16 ê 4 × T æç ö÷ + + Q T æç ö÷ = 4T æç ö÷ +
è 27 ø 81 ú 9 è 9ø è 27 ø 81
ë û
n n 2 13n 2
= 64T æç ö÷ + 16 × +
è 27 ø 81 9
n 133n 2
= 64T æç ö÷ +
è 27 ø 81
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 36 Introduction to Algorithm and Data Structures
2
æ n ö æ n ö
= 4 3T ç ÷ + 133 ×ç ÷
è 33 ø è 32 ø
M
2
æ n ö æ n ö
= 4 kT ç ÷ + C ç k- 1 ÷ Q 133 + C 1 = C
è 3k ø è3 ø
n
Now if we assume = 1 then n = 3 k and k = log 3 n
3k
2
æ n ö n
= 4 k T(1) + C ç ÷ Q = 1
è 3k - 1 ø 3k
C
= 4 k + C1 × n 2 Q C1 =
k- 1 2
(3 )
= 4 log 3 n + C 1 n 2
= n 1.26 + C × n 2
T(n) » Q (n 2 )
n
T(n) = 2T æç ö÷ + C
è 2ø
æ n ö
= 2 ç 2T æç ö÷ + C÷ + C
è è 4 ø ø
n
= 4T æç ö÷ + 3C
è4ø
æ n ö
= 4 ç 2T æç ö÷ + C÷ + 3C
è è 8ø ø
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 37 Introduction to Algorithm and Data Structures
n
= 8T æç ö÷ + 7C
è 8ø
æ n ö
= 2 3Tç 3
÷ + (2 - 1) C
èn3ø
M
æ n ö
T(n) = 2 k T ç ÷ + (2 k - 1) C
è 2k ø
If we 2 k = n then
n
T(n) = nT æç ö÷ + (n - 1) C
è nø
= nT(1) + (n – 1) C
T(n) = n + (n – 1) C Q T(1) = 1
ii) Let,
n
T(n) = T æç ö÷ + C
è 3ø
æ n ö
= ç T æç ö÷ + C÷ + C
è è 9ø ø
n
= T æç ö÷ + 2C
è 9ø
é n ù
= êT æç ö÷ + Cú + 2C
ë è 27 ø û
n
= T æç ö÷ + 3C
è 27 ø
M
æ n ö
= T ç ÷ + kC
è 3k ø
If we put 3 k = n then
n
= T æç ö÷ + log 3 n × C
è nø
= T (1) + log 3 n × C
T(n) = C × log 3 n + 1 Q T(1) = 1
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 38 Introduction to Algorithm and Data Structures
Solution : Let
T(n) = T(n – 1) + n 4
= T(n - 2) + (n - 1) 4 + n 4
= [T(n - 3) + (n - 2) 4 ] + (n - 1) 4 + n 4
= T(n - 3) + (n - 2) 4 + (n - 1) 4 + n 4
= [T(n - 4) + (n - 3) 4 ] + (n - 2) 4 + (n - 1) 4 + n 4
= T(n - 4) + (n - 3) 4 + (n - 2) 4 + (n - 1) 4 + n 4
= T(n - k) + (n - k + 1) 4 + (n - k + 2) 4 + (n - k + 3) 4 + K n 4
If k = n then
= T(n - n) + (n - n + 1) 4 (n - n + 2) 4 + (n - n + 3) 4 + L + n 4
= T(0) + 1 4 + 2 4 + 3 4 + K + n 4
n
= T(0) + å n4
i= 1
n n
= T(0) + n(n 4 ) Q å n4 = n4 × å 1 = n4 ×n
i= 1 i= 1
\ T(n) » q(n 5 )
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 39 Introduction to Algorithm and Data Structures
Solution : In the above code the following statement gets executed at least twice
count = count + 1
In the else part, there is a recursive call to the function sum, by changing the value
of n by n – 1, each time.
Hence the recursive formula for above code will be
T(n) = T(n – 1) + 2
For count
For recursive
statement
call to function
sum in else
part.
T(0) = 2
= [T(n – 2) + 2] + 2
\ = T (n – 2)+2(2)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 40 Introduction to Algorithm and Data Structures
= T(0) + 2n
= 2+2×n Q T(0) = 2
T(n) = 2(n+1)
We can denote the time complexity in the form of big oh notation as O(n).
1. T(n) = Q (n d ) if a < b d
2. T(n) = Q (n d log n) if a = b
log ba
3. T(n) = Q (n ) if a > b d
= Q (n 2 ) Q log 2 4 = 2
For quick and easy calculations of logarithmic values to base 2 following table can
be memorized.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 41 Introduction to Algorithm and Data Structures
m k
1 0
2 1
4 2
8 3
16 4
32 5
64 6
128 7
256 8
512 9
1024 10
log ba - e
1. If f(n) is O (n ), then
log ba
T(n) = Q (n )
log ba
2. If f(n) is Q (n log k n), then
log ba
T(n) = Q (n log k+ 1 n)
log ba + e
3. If f(n) is W (n ), then
T(n) is = Q (f(n))
Example 1.14.7 Solve the following recurrence relation. T(n) = 2T(n/2) + n log n
Solution :
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 42 Introduction to Algorithm and Data Structures
= Q (n 1 log 2 n)
\ T(n) = Q (n log 2 n)
Solution :
Here f(n) = n 2
a = 8 and b = 2
\ log 2 8 = 3
T(n) = Q (n 3 )
Solution :
Here a = 9, b=3 and f(n) = n 3
And log 3 9 = 2
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 43 Introduction to Algorithm and Data Structures
and log 2 1 = 0
= Q (n 0 × 1)
= Q (1) Q n0 = 1
log ba
\ We get T(n) = Q (n log k+ 1 n)
log 2 1
= Q (n log 0+ 1 n)
= Q (n 0 × log 1 n)
T(n) = Q (log n) Q n0 = 1
Example 1.14.11 Find the complexity of the following recurrence relation. T(n) = 9T(n/3) + n
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 44 Introduction to Algorithm and Data Structures
log b a
T(n) = Q (n )
= Q (n log 3 9 )
T(n) = Q (n 2 )
n
T(n) = k × T æç ö÷ + n 2 be a recurrence relation. Let us use substiturion
è kø
method
é n n2 ù
= 2 ê 2 × T æç ö÷ + ú+n
2
ë è 4 ø 4 û
n n2
= 4T æç ö÷ + + n2
è4ø 2
2
n 3n 2 n n n
= 4T æç ö÷ + T æç ö÷ = 2T æç ö÷ + æç ö÷
è4ø 2 è4ø è 8ø è 4ø
é n n 2 ù 3n 2
= 4 ê 2 × T æç ö÷ + +
ë è 8 ø 16 úû 2
n n 2 3n 2
= 8T æç ö÷ + +
è 8ø 4 2
2
n 7n
= 8T æç ö÷ +
è 8ø 4
æ n ö 2k - 1 2
= 2kT ç ÷ + n
è 2k ø 2k - 1
æ n ö 2k - 1
= 2 k T ç ÷ + Cn 2 Q = C = Constant
è 2k ø 2 k- 1
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 45 Introduction to Algorithm and Data Structures
n
If we put = 1 then 2 k = n and k = log 2 n
2k
= nT(1) + Cn 2
= n + Cn 2 Q T(1) = 1
T(n) = Q (n) 2
Alternate Method
We can solve the given recurrence relation using Master's theorem also.
n
T(n) = k × T æç ö÷ + n 2
è kø
¯ ¯ ¯
a b f(n)
log b a
By Master's theorem n = n log k k = n 1
= n1+ 1 when e = 1
= f(n) i. e. n 2
\ T(n) = Q(f(n))
T(n) = Q(n 2 )
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 46 Introduction to Algorithm and Data Structures
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.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 47 Introduction to Algorithm and Data Structures
P n (n + 1)
= + n (1 - P)
n 2
P (n + 1)
C avg (n) = + n (1 - P)
2
Thus we can obtain the general formula for computing average case time complexity.
Suppose if P = 0 that means there is no successful search i.e. we have scanned the
entire list of n elements and still we do not found the desired element in the list then in
such a situation,
C avg (n) = 0(n + 1)/2 + n (1 – 0)
C avg (n) = n
Thus the average case running time complexity becomes equal to n.
Suppose if P = 1 i.e. we get a successful search then
C avg (n) = 1 (n + 1)/2 + n (1 – 1)
C avg (n) = (n + 1)/2
That means the algorithm scans about half of the elements from the list.
For calculating average case time complexity we have to consider probability of
getting success of the operation. And any operation in the algorithm is heavily
dependent on input elements. Thus computing average case time complexity is difficult
than computing worst case and best case time complexities.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 48 Introduction to Algorithm and Data Structures
¡ Greedy Technique : To solve the problem locally optimal decisions are made.
¡ Backtracking : In this method, we start with one possible move out from many
moves out and if the solution is not possible through the selected move then we
backtrack for another move.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 49 Introduction to Algorithm and Data Structures
70 20 30 40 10 50 60
Divide Divide
70 20 30 40 10 50 60
Divide Divide
70 20 30 40 10 50 60
Divide Divide
70 20 30 40 10 50 60
Merge Merge
20 70 30 10 40 50 60
Merge Merge
20 30 70 10 40 50 60
Merge Merge
10 20 30 40 50 60 70
Fig. 1.16.2
Pseudo Code
Algorithm MergeSort(int A[0…n-1],low,high)
//Problem Description: This algorithm is for sorting the
//elements using merge sort
//Input: Array A of unsorted elements, low as beginning
//pointer of array A and high as end pointer of array A
//Output: Sorted array A[0…n-1]
if(low < high)then
{
mid ¬ low+high)/2 //split the list at mid
MergeSort(A,low,mid) //first sublist
MergeSort(A,mid+1,high) //second sublist
Combine(A,low,mid,high) //merging of two sublists
}
Algorithm Combine(A[0…n-1],low, mid, high)
{
k ¬ low; //k as index for array temp
i ¬ low; //i as index for left sublist of array A
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 50 Introduction to Algorithm and Data Structures
Logic Explanation
To understand above algorithm consider a list of elements as
70 20 30 40 10 50 60
0 1 2 3 4 5 6
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 51 Introduction to Algorithm and Data Structures
low high
0 1 2 3 4 5 6
70 20 30 40 10 50 60 Merge sort (A, low, mid)
4
1 This list is further
subdivided This list can be
subdivided
0 1 2 3
70 20 30 40
2 This list is
3 This list
subdivided can be Merge sort (A, mid+1, high)
subdivided
70 20 30 40 10 50 60
This list
7 Combine 5 can be
Combine two
subdivide
As A[j] < A[i] sublists in
copy A[j] to temp array 6 10 50 10
temp Combine two
sublists
20 70 30 40 9 Combine two
sublists
8 Combine
these two 10 50
20 30 40 70 sublists
10 50 60
11 Combine two
sublists
10 20 30 40 50 60 70
Fig. 1.16.3
Let us see the combine operation more closely with the help of some example.
Consider that at some instance we have got two sublits 20, 30, 40, 70 and 10, 50, 60,
then
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 52 Introduction to Algorithm and Data Structures
i j
if (A[i]<= A[j])
Initially k = 0. Then k will be incremented {
temp[k] A[i]
temp i i+1
10 k k+1
}
0 el else
k get s e p a r t
s ex o {
ecute f a l g o r ith m
d temp[k] A[j]
j j+1
Note that A (left sublist) A (right sublist)
k k+1
i remains }
there and j is 20 30 40 70 10 50 60
incremented
i j
i j
k = 1. It is advanced later on
if (A[i]<= A[j])
temp {
10 20 temp [k] A[i]
if part of algorithm i i+1
0 1
gets executed k k+1
k
moves ahead }
else
{
Note that Array A (left sublist) Array A (right sublist) temp [k] A[j]
j remains there j j+1
and only i is 20 30 40 70 10 50 60
k k+1
incremented
}
i j
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 53 Introduction to Algorithm and Data Structures
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 54 Introduction to Algorithm and Data Structures
Finally we will copy all the elements of array temp to array A. Thus array A
contains sorted list.
A
10 20 30 40 50 60 70
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 55 Introduction to Algorithm and Data Structures
3. From the set of feasible solutions, particular solution that satisfies or nearly
satisfies the objective of the function. Such a solution is called optimal solution.
4. As Greedy method works in stages. At each stage only one input is considered
at each time. Based on this input it is decided whether particular input gives
the optimal solution or not.
Now we will consider each vertex as a source and will find the shortest distance
from this vertex to every other remaining vertex. Let us start with vertex A.
D D-E, path = 7 + 8 = 15
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 1 - 56 Introduction to Algorithm and Data Structures
Pseudo Code
Algorithm Dijkstra(int cost[1…n,1…n],int source,int dist[])
for i ¬ 0 to tot_nodes
{
dist[i] ¬ cost[source,i]//initially put the
s[i] ¬ 0 //distance from source vertex to i
//i is varied for each vertex
path[i] ¬ source//all the sources are put in path
}
s[source] ¬ 1 Start from each source node
for(i ¬ 1 to tot_nodes)
{
min_dist ¬ infinity;
v1 ¬ -1//reset previous value of v1
for(j ¬ 0 to tot_nodes-1)
{
Finding minimum
if(s[j]=0)then distance from
{ selected source
if(dist[j]<min_dist)then node.That is :
{ source-j represents
min_dist. edge
min_dist ¬ dist[j]
v1 ¬ j
}
}
}
s[v1] ¬ 1
for(v2 ¬ 0 to tot_nodes-1)
{
if(s[v2]=0)then
{
if(dist[v1]+cost[v1][v2]<dist[v2])then
{
dist[v2] ¬ dist[v1]+cost[v1][v2]
path[v2] ¬ v1
} v1 is next selected destination
} vertex with shortest distance.
All such vertices are
} accumulated in array
} path[ ]
}
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge