MCS-211 · Block 1 Unit 1

Basics of an Algorithm and its Properties

Section 4 of 9

Block 1 · Unit 1Basics of an Algorithm and its Properties11 min · Section 4 of 9

1.4Common Running Times: Constant to Cubic

Covers IGNOU MCS-211 §1.4

Many algorithms can solve the same problem, so we need a fair way to compare them. This page explains how running time is measured and introduces the most common “polynomial” running times, with the loop shapes that produce them.

Measuring running time

Measuring seconds on a stopwatch is unfair: the result depends on the computer, the compiler and the other programs running. Instead we count the number of basic operations as a function of the input size.

We usually care about how T(n)T(n) grows as nn becomes large, and we ignore constant factors. That is why we write T(n)=O(n)T(n) = O(n) (read “big-O of nn”) rather than T(n)=3n+2T(n) = 3n + 2. Big-O is defined formally in Section “Analysis of Algorithms” and in Unit 2; for now read O(g(n))O(g(n)) as “grows at most like g(n)g(n)”.

The classes

ClassNameTypical loop shapeExample
O(1)O(1)ConstantNo loop over the inputRead a[i]; push onto a stack
O(log⁡n)O(\log n)LogarithmicProblem size halves each stepBinary search
O(n)O(n)LinearOne pass over the inputFind the minimum of an array
O(nlog⁡n)O(n \log n)LinearithmicSplit in halves, do linear work per levelMerge sort, heap sort
O(n2)O(n^2)QuadraticTwo nested loops over the inputBubble, selection, insertion sort (worst case)
O(n3)O(n^3)CubicThree nested loopsNaive matrix multiplication; the disjoint-sets example below

Constant time, O(1)O(1)

The number of steps does not depend on nn. Swapping two variables or reading the first element of an array takes the same time whether the array has 10 elements or 10 million.

Logarithmic time, O(log⁡n)O(\log n)

If each step halves the remaining problem, the number of steps is about log⁡2n\log_2 n. Binary search in a sorted array is the standard example.

Linear time, O(n)O(n)

The algorithm does a constant amount of work for each input element, usually in one pass. Finding the minimum:

Minimum pseudocode
minimum ← a[1]
for i ← 2 to n do
    if a[i] < minimum then
        minimum ← a[i]
    end if
end for

This makes exactly n−1n - 1 comparisons, so T(n)=n−1=O(n)T(n) = n - 1 = O(n).

Linearithmic time, O(nlog⁡n)O(n \log n)

Divide-and-conquer sorting algorithms such as merge sort split the array into halves (about log⁡2n\log_2 n levels of splitting) and do O(n)O(n) work to merge on each level, giving O(nlog⁡n)O(n \log n) in total. It grows only slightly faster than linear time and is the best possible for sorting by comparisons.

Quadratic time, O(n2)O(n^2)

Two nested loops, each running up to nn times, perform up to n×n=n2n \times n = n^2 inner steps. Simple sorting algorithms (bubble, selection, insertion) are quadratic in the worst case. Quadratic algorithms are fine for small inputs but become slow for large ones.

Cubic time, O(n3)O(n^3)

Three nested loops give up to n3n^3 steps. The study material’s example: given nn sets S1,…,SnS_1, \dots, S_n, each with nn elements, decide whether some pair of the sets is disjoint (has no common element).

Disjoint pair pseudocode
for each set S_i do
    for each other set S_j do
        common ← false
        for each element x of S_i do
            if x belongs to S_j then        // O(1) test, see below
                common ← true
            end if
        end for
        if common = false then
            print "S_i and S_j are disjoint"
        end if
    end for
end for

There are nn choices of SiS_i, at most nn choices of SjS_j and nn elements xx, so at most n⋅n⋅n=n3n \cdot n \cdot n = n^3 membership tests. The analysis assumes each test “is xx in SjS_j?” takes constant time, for example by storing each set as a true/false table indexed by element. If the test instead scanned SjS_j element by element, it would cost O(n)O(n) and the total would become O(n4)O(n^4).

C · disjoint_pair.c
#include <stdio.h>
#include <stdbool.h>

#define N 4   /* number of sets, and size of each set */
#define U 16  /* elements are numbers 0..U-1 */

/* member[i][x] is true when x is in set S_i.
   This table makes the test "is x in S_j?" take O(1) time. */
static bool member[N][U];

int main(void)
{
    int sets[N][N] = {
        {1, 2, 3, 4},
        {4, 5, 6, 7},
        {8, 9, 10, 11},
        {3, 9, 12, 13}
    };
    long checks = 0;

    for (int i = 0; i < N; i++)
        for (int k = 0; k < N; k++)
            member[i][sets[i][k]] = true;

    for (int i = 0; i < N; i++) {                 /* each set S_i        */
        for (int j = i + 1; j < N; j++) {         /* each other set S_j  */
            bool common = false;
            for (int k = 0; k < N; k++) {         /* each element x of S_i */
                checks++;
                if (member[j][sets[i][k]]) {      /* O(1) membership test */
                    common = true;
                    break;
                }
            }
            if (!common)
                printf("S%d and S%d are disjoint\n", i + 1, j + 1);
        }
    }
    printf("membership checks: %ld (at most n^3 = %d)\n", checks, N * N * N);
    return 0;
}
Output
S1 and S3 are disjoint
S2 and S3 are disjoint
S2 and S4 are disjoint
membership checks: 21 (at most n^3 = 64)

The program checks each unordered pair once (j > i) and stops early when it finds a common element, so it uses fewer than n3n^3 checks; n3n^3 is the upper bound.

Counting steps for each loop shape

C · count_steps.c
#include <stdio.h>

/* Counts how many times the innermost statement runs
   for loop shapes that give common running times. */
int main(void)
{
    int n = 16;
    long constant = 0, logarithmic = 0, linear = 0, quadratic = 0, cubic = 0;

    constant++;                                   /* O(1): one step, any n */

    for (int size = n; size > 1; size /= 2)       /* O(log n): halve each time */
        logarithmic++;

    for (int i = 0; i < n; i++)                   /* O(n): one pass */
        linear++;

    for (int i = 0; i < n; i++)                   /* O(n^2): two nested loops */
        for (int j = 0; j < n; j++)
            quadratic++;

    for (int i = 0; i < n; i++)                   /* O(n^3): three nested loops */
        for (int j = 0; j < n; j++)
            for (int k = 0; k < n; k++)
                cubic++;

    printf("n = %d\n", n);
    printf("constant    : %ld\n", constant);
    printf("logarithmic : %ld\n", logarithmic);
    printf("linear      : %ld\n", linear);
    printf("quadratic   : %ld\n", quadratic);
    printf("cubic       : %ld\n", cubic);
    return 0;
}
Output
n = 16
constant    : 1
logarithmic : 4
linear      : 16
quadratic   : 256
cubic       : 4096

Key takeaways

  • Running time T(n)T(n) counts basic operations as a function of input size nn.
  • Constant factors are ignored inside big-O: write O(1)O(1) and O(n)O(n), not O(k)O(k) and O(kn)O(kn).
  • Halving gives O(log⁡n)O(\log n); one pass gives O(n)O(n); nested loops multiply.
  • The O(n3)O(n^3) disjoint-sets bound assumes O(1)O(1) membership tests.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

An algorithm reads only the first and last elements of an array of size nn. Its running time is:

Show answer

Answer: A. O(1)O(1)

Two steps regardless of n is constant time. O(2) and O(1) are the same class because constants are dropped.

Question 2 · multiple choice

How many times does the loop body run for n = 100 in for (size = n; size > 1; size /= 2) (integer division)?

Show answer

Answer: C. 6

size takes the values 100, 50, 25, 12, 6, 3 (body runs) and then 1 (loop stops): 6 times. About log₂100 ≈ 6.6, rounded down.

Question 3 · multiple choice

What does this program print?

C · quiz_triangle.c
#include <stdio.h>

int main(void)
{
    int n = 4, count = 0;
    for (int i = 0; i < n; i++)
        for (int j = i; j < n; j++)
            count++;
    printf("%d\n", count);
    return 0;
}
Show answer

Answer: D. 10

The inner loop runs 4 + 3 + 2 + 1 = 10 times, which is n(n+1)/2. The answer 16 would be the full square n².

Question 4 · multiple choice

Merge sort runs in which class?

Show answer

Answer: C. O(nlog⁡n)O(n \log n)

It has about log₂n levels of halving with O(n) merging work on each level. It is not logarithmic: it must at least look at all n elements.

Question 5 · multiple choice

In the disjoint-sets example, what is the total cost if each membership test scans SjS_j and costs O(n)O(n)?

Show answer

Answer: C. O(n4)O(n^4)

n³ tests × O(n) per test = O(n⁴). The O(n³) bound holds only when each test is O(1).

Question 6 · short answer

Find the number of times x ← x + 1 runs in: for i ← 1 to n do for j ← 1 to n do for k ← 1 to n do x ← x + 1. Give its class.

Show worked answer

The three loops are independent and each runs n times, so the statement runs n × n × n = n³ times. The running time is O(n³) (cubic). For n = 10 that is 1000 executions.

↑ ↓ move↵ openTab switch type