Space and Time Complexity
Space and Time Complexity
• developing a formula for predicting how fast an algorithm is, based on the
size of the input (time complexity),
and/or
• developing a formula for predicting how much memory an algorithm requires,
based on the size of the input (space complexity).
3. Instruction Space: Space needed to store the compiled version of the program instruction
• Compiler Dependent
• S = C + Sp(size of the input), where c denotes fixed part and Sp denotes the
variable component
int sum (int a[], int n) int Rsum (int a[], int n)
{ {
int result; if (n > 0)
for(int i=0; i<n; i++) return Rsum(a, n-1) + a[n-1];
result= result + a[i];
return result; return 0;
} }
Rsum(a, n) Rsum(a, n-1)
….Rsum(a,1), Rsum(a, 0)
therefore, depth= n+1
Sp(n) = 0 constant time
O(1) Sp(n) = 12 (n+1) bytes
03/23/2022
=O(n)
ICT 2257 Design and Analysis of Algorithms
Data Space Examples
i. Int *a;
a = new int [n]; Space needed 4n Bytes (n integers, each need 4 Bytes)
• Examples
• Matrix multiplication:
• Key operations are addition and multiplications
• Sorting:
• Key operations are comparison and swapping.
• Searching:
• Comparison
delete [] u;
}
03/23/2022 ICT 2257 Design and Analysis of Algorithms
Selection and Bubble Sort
a[i+1] = x; // insert x
}
Key operation Comparison Total comparison = n Complexity: O(n)
03/23/2022 ICT 2257 Design and Analysis of Algorithms
Insertion Sort
void insert(int a[], int n, const int& x)
{
for (int i = n-1; i >= 0 && x < a[i]; i--)
a[i+1] = a[i];
a[i+1] = x;
}
a[j + 1] = t; 1 n-1n-1
}
} Total Steps = n2 – 3n – 3 = O(n2)
03/23/2022 ICT 2257 Design and Analysis of Algorithms
void selectionSort(int a[], int n)
{
for (int size = n; size > 1; size--)
{
int j = 0, temp;
for (int k = 1; k < size; k++)
{
if (a[j] < a[k])
j = k;
}
temp=a[j];
a[j]=a[size-1];
a[size-1]=temp;
}
}
2. int x=0;
for(int i=0; i<m; i++)
for (int j=0; j<n; j++)
for(int k=0; k<p; k++)
x = x+1;
What is the final value of x? how many times for loop for k will execute?
03/23/2022 ICT 2257 Design and Analysis of Algorithms
Step Count Method: Few more examples
i. int a = 0;
for (i = 0; i < N; i++) {
for (j = N; j > i; j--) {
a = a + i + j;
}
}
03/23/2022 ICT 2257 Design and Analysis of Algorithms
Reference:
• Sartaj Sahani, Data Structures Algorithms and Applications in C++,
Second Edition, Universities Press (India) Private Ltd, 2005.