Open In App

Step Count Method for Time Complexity Analysis

What is Time Complexity?

Time Complexity is the amount of time taken by the algorithm to run. It measures the time taken to execute each statement of code in an algorithm.

Time Complexity can be calculated by using Two types of methods. They are:



Here, we will discuss the Step Count Method.

What is Step Count Method?

The step count method is one of the methods to analyze the Time complexity of an algorithm. In this method, we count the number of times each instruction is executed. Based on that we will calculate the Time Complexity. 



The step Count method is also called as Frequency Count method. Let us discuss step count for different statements:

1. Comments:

2. Conditional statements:

Conditional statements check the condition and if the condition is correct then the conditional subpart will be executed. So the execution of conditional statements happens only once. The compiler will execute the conditional statements to check whether the condition is correct or not so it will be executed one time.

3. Loop statements:

Loop statements are iterative statements. They are executed one or more times based on a given condition.

4. Functions:

Functions are executed based on the number of times they get called. If they get called n times they will be executed n times. If they are not called at least once then they will not be executed. Other statements like BEGIN, END and goto statements will be executed one time.

Illustration of Step Count Method:

Analysis of Linear Search algorithm

Let us consider a Linear Search Algorithm.

Linearsearch(arr, n, key)                                 
{                                                       
    i = 0;
    for(i = 0; i < n; i++)
    { 
        if(arr[i] == key)
        {
            printf(“Found”);
        }
}

Where,

Therefore Total Number of times it is executed is n + 4 times. As we ignore lower exponents in time complexity total time became O(n).

Time complexity: O(n).
Auxiliary Space: O(1)

Linear Search in Matrix

Searching for an element in a matrix

Algo Matrixsearch(mat[][], key)

    // number of rows;
    r := len(mat)

    // number of columns;
    c := len(mat[0])     

    for(i = 0; i < r; i++)
    {
        for(j = 0;  j < c;  j++)
        {
            if(mat[i][j] == key)
            {
                printf(“Element found”);
            }
        }
    }
}

Where,

Therefore Total Number of times it is executed is (1 + 1 + (r + 1) + (r) * (c + 1) + 1) times. As we ignore the lower exponents, total complexity became O(r * (c + 1)).

the mat is an array so it takes n*n words , k, c, r, i, j will take 1 word.

Time Complexity: O(n2).

Auxiliary Space: O(n2)

In this way, we calculate the time complexity by counting the number of times each line executes.

Advantages of using this method over others:

Related Articles:

Article Tags :