Professional Documents
Culture Documents
ALGORITHM
ALGORITHM
•Performance often draws the line between what is feasible and what is
impossible.
• Speed is fun!
5/7/2022 Prepared by: Asst. Prof. Lokesh Sahu
• How to do Analysis?
Time taken depends on 2 factors
1. Machine or Hardware dependent
2. Platform or Software dependent
Types of Analysis
1. Apriori Analysis : Machine and Platform independent
2. Apostriori Analysis : Machine and Platform dependent
A function mapping
“size” of input
w.r.to. inputs
• Best case
• Average case
• Worst case
Note: Choosing what kind of input to be consider when analyzing an
algorithm have a significant impact on the behaviour of Algorithm.
BIG IDEA:
• Ignore machine-dependent constants.
• Look at growth of T(n) as n ─> ∞
“Asymptotic Analysis”
•Asymptotic analysis are input bound i.e., if there's no input to the algorithm it
is concluded to work in a constant time. Other than the "input" all other
factors are considered constant.
• Using asymptotic analysis, we can very well conclude the best case,
average case and worst case scenario of an algorithm.
i=1
Ex 4: calculate frequency count for:
While(i<=n) For(i=0;i<n;i++)
For(j=0;j<n;j++)
{ for(k=0;k<n;k++)
x=x+1; x=x+1;
Ans: O(n^3)
i=i+1;
}
Ans: 3n+2 = O(n)
• Ex 4: calculate frequency count for:
main() int i, j, k = 0;
for (i = n / 2; i <= n; i++) {
{ for (j = 2; j <= n; j = j * 2) {
k = k + n / 2;
i=n; }
While(i>=1) }
{ O(n)
O(nLogn)
i=i/2; O(n^2)
} O(n^2Logn)
}
Ans: O(log n)
• Ex 4: calculate frequency count for:
Main()
{
For( i= 1 to n)
{
For( j=1 to n )
{
For (k=1 to 165)
{
X=Y+Z;
}}}}
• Ans: O(n^2)
Space Complexity
• Space Complexity of an algorithm is the total space taken by the
algorithm with respect to the input size. Space complexity includes
both Auxiliary space and space used by input.
• Auxiliary Space is the extra space or temporary space used by an
algorithm.
Example
• int add (int n){
• if (n <= 0){
• return 0;
• }
• return n + add (n-1);
• }
1. add(4)
2. -> add(3)
3. -> add(2)
4. -> add(1)
5. -> add(0)
Each of these calls is added to call stack and takes up actual memory.
So it takes O(n) space.
Example-2
• int main(){
• int n, i, sum = 0;
• scanf("%d", &n);
• int arr[n];
• for(i = 0; i < n; i++)
• {
• scanf("%d", &arr[i]);
• sum = sum + arr[i];
• }
• printf("%d", sum);
• }
Space Requirement: the array consists of n integer elements. So, the space occupied by
the array is 4 * n. Also we have integer variables such as n, i and sum. Assuming 4 bytes for
each variable, the total space occupied by the program is 4n + 12 bytes. Since the highest
order of n in the equation 4n + 12 is n, so the space complexity is O(n) or linear.