Chapter 1 - Introduction
Chapter 1 - Introduction
Algorithms
The model defines an abstract view to the problem. This implies that
the model focuses only on problem related stuff and that a
programmer tries to define the properties of the problem.
These properties include
The data which are affected and
The operations that are involved in the problem.
B. sum=0;
for(i=1;i<=n;i++)
for(j=1;j<=i;j++)
sum++;
Algorithm Analysis Categories
• Algorithm must be examined under different
situations to correctly determine their
efficiency for accurate comparisons
• Best Case Analysis: Assumes that data
are arranged in the most advantageous
order. It also assumes the minimum input
size.
• E.g.
• For sorting – the best case is if the data are
arranged in the required order.
• For searching – the required item is found at the
first position.
• Note: Best Case computes the lower
boundary of T(n)
Worst case analysis
• Assumes that data are arranged in the
disadvantageous order.
• It also assumes that the input size is infinite.
• E.g.
• For sorting – data are arranged in opposite
required order
• For searching – the required item is found at
the end of the item or the item is missing
• It computes the upper bound of T(n) and
causes maximum number of execution.
Average case Analysis
Assumes that data are found in random
order.
It also assumes random or average input
size.
E.g.
For sorting – data are in random order.
For searching – the required item is found
at any position or missing.
It computes optimal bound of T(n)
It also causes average number of
execution.
Best case and average case can not be
used to estimate (determine) complexity of
Cont.
T(n) = 1+n+1+n+n
= 3n+2
T(n) = O(n)
Exercise
Find Big O of the following algorithm
1. for(i=1;i<=n;i++)
Sum=sum+i;
For (i=1;i<=n;i++)
For(j=1;j<=m;j++)
Sum++;
…
2. if(k==1)
{
For (i=1;i<=100;i++)
For (j=1;j<=1000;j++)
Cout<<I
}
Else if(k==2)
{
For(i=1;i<=n;i=i*2)
Cout<<i;
}
Else
{
{for (i=1;i<=n;i++)
Sum++;
}
…
3. for (i=1; i<=n;i++)
{
If (i<10)
For(j=1;j<=n;j=j*2)
Cout<<j;
Else
Cout<<i;
}
…
4. for (int i=1; i<=N; ++i)
for (int j=i; j>0; --j){}
5. for (int i=1; i<N; i=i*2){}
6. for (int i=0; i<N; ++i)
for (int j=i; j>0; j=j/2){}
…