How the program utilizes data and how they put the data in inside the main memory? ↓ ↓ ↓
Here we will discuss the following:
Difference between Physical and Logical DS ↓
Let us take an example of list that is collection of elements.
Either from procedure or program code we can find time complexity.
for(i = 0; i < n; i++)
{
// searching
// adding
}
// here 'i' goes from 0 to 'n' so it is O(n).
For each element in a list if there is again a comparision that means there are two for loop, one inside another with O(n2) time complexity.
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
// processing
}
}
for(i = 0; i < n; i++)
{
for(j = i+1; j < n; j++)
{
// processing
}
}
// O(n^2)
When a list is successively divide in two half until it reaches 1 that is represented as log2 n
for(i = n; i > 1; i = 1/2)
{
// processing
}
// O(log n)
// matrix processing code
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
// processing
}
}
void swap(x, y)
{
int t;
t = x; // 1
x = y; // 1
y = t;// 1, each statement take 1 unit of time as it is simple assignment.
}
time f(n) = 1 + 1 + 1
= 3 (constant)
= O(1)
int sum(int A[], int n)
{
int s, i;
s = 0; // 1 unit
for( i = 0; i < n; i++) // condition will be checked for n + 1 time and increment will be n time so total = n + 1 + n + 1 = 2(n + 1)
{ // i = 0 assignment = 1 time
s = s + A[i]; // n
}
return s; // 1
}
/* total = 1 + 2(n+1) + n + 1
= 1 + 2n + 1 + n + 1
= 3n + 3
= O(n) as the degree of n is 1 */
void Add(int n)
int i, j;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
// O(n^2)
fun1()
{
fun2();
}
fun2()
{
for(i = 0; i < n; i++)
{
// processing
}
}
// O(n)