0% found this document useful (0 votes)
23 views

Algorithm 6th Lecture

The document discusses time complexities of various algorithms. It analyzes loops and nested loops to determine the overall time complexity of algorithms. Some algorithms discussed have time complexities of O(n), O(n^2), O(log n). The last algorithm finds the maximum subsequence sum in an array and has a time complexity of O(n^3).

Uploaded by

noah87619
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Algorithm 6th Lecture

The document discusses time complexities of various algorithms. It analyzes loops and nested loops to determine the overall time complexity of algorithms. Some algorithms discussed have time complexities of O(n), O(n^2), O(log n). The last algorithm finds the maximum subsequence sum in an array and has a time complexity of O(n^3).

Uploaded by

noah87619
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Design and Analysis of

Algorithm
Algorithm Swapping(a,b)
{
 int temp = a; 1
 a = b; 1
 b = temp;
1
} T(n)= 3
Variable: a, b, temp
Space Complexity= S(n) = 3
for (int i=0;i<n;i++)
{
sum = sum + i;
}
T(n) = n

T(n) = O(n)
1 ; n/5+1 ; n/5
for (int i=0;i<n;i++) for (int i=0;i<n;i+=5)
{
{
n/5 sum + =i; 2(n/5)
sum + =i; }
n/5+1+2(n/5)
} =n/5+2n/5+1
=3n/5+1
=3n/5= n/5
=n
T(n) = n
T(n) = n/5

T(n) = O(n) T(n) = O(n)


1 ;n+1 ; n  n+1
for (int i=0;i<n;i ++)
{ 1; n+1; n  n(n+1)=n2+n
for (int j=0;j<n; j ++)
n {
n sum + = j; 2 2n
}
}
N+1+n2+n+2n
= n2+4n+1
= n2+n
=n2

T(n) = O(n2)
for (int i=0;i<n;i ++)
sum + =i;
for (int i=0;i<n; i ++)
sum + =i;

T(n) = O(n)
int i=0; 1
while (i<n) n
{
int j=0; 1
while (j<n) n
{
3n sum + =i; 2
j ++; 1
}
i ++;
}
T(n) = O(n2)
1 ; n; n=16, i=1,i=2,i=4,i=8,i=16,i=32 =log2^5
1 ; logn+1; logn
for (int i=1;i<n; i * 2)
{
sum + =i; 2logn
}
Logn+1 +2Logn
Logn+2logn =3logn
logn

T(n) = O(log2n)
Example 1
 Analyze Time for the following algorithm

MaxElement(A[0..n-1)
{
maxVal = A[0]; 1
1 ; n-1 ; n
for(i = 1; i < n; i++) n
if(A[i] > maxVal) n
maxVal = A[i]; 0, n
return maxVal 1
}
1+n+n+n +1=
3n+2= 3n= n
[email protected] 9
Example 2

Analyze Time for the following algorithm

UniqueElements(A[0..n-1])
for(i= 0; i<n; i++)
for(j = 0; j<n; j++)
if(A[i] = A[j])
return false
return true

[email protected] 10
Analyze Time for the following algorithm
Max_Subsequence_Sum(Array, N) //Where N is size of Array
{
int sum = 0, Max_sum = 0; 2
for(int i = 0; i < N; i++) n+1
{
for(int j = i; j < N; j++) n+1
{
sum = 0; 1
for(int k = i; k <= j; k++) n+1
sum = sum + Array[k]; 3
if(sum > Max_sum) 1
Max_sum = sum; 1
}

}
return(Max_sum); 1
}

You might also like