MCS-211 · Block 1 Unit 1

Basics of an Algorithm and its Properties

Section 6 of 9

Block 1 · Unit 1Basics of an Algorithm and its Properties13 min · Section 6 of 9

1.6Analysis of Algorithms: Best, Worst and Average Case

Covers IGNOU MCS-211 §1.5

Knowing that one algorithm is “faster” is not enough; we need to say how much faster and on which inputs. This page defines time and space complexity, shows how the same algorithm can behave differently on different inputs of the same size, and introduces the notations used to describe growth.

Time and space complexity

The study of how much time and memory algorithms use is called analysis of algorithms; the term was introduced by Donald Knuth.

A key operation (basic operation) is the operation that dominates the running time, chosen so that every other operation is done at most a constant number of times per key operation. For searching and sorting, the key operation is the comparison of two elements. Unless stated otherwise, “complexity” means time complexity.

Three cases

For many algorithms, inputs of the same size need different numbers of steps. Searching for a key that is at the front of an array is quicker than searching for one at the back.

CaseMeaningWhy we study it
Worst case Cworst(n)C_{\text{worst}}(n)Maximum number of key operations over all inputs of size nnA guarantee: the algorithm never does worse. Used by default.
Best case Cbest(n)C_{\text{best}}(n)Minimum number over all inputs of size nnShows the most favourable inputs; rarely a guarantee of anything.
Average case Cavg(n)C_{\text{avg}}(n)Expected value of the number of key operations, under a stated probability distribution of inputsDescribes typical behaviour; harder to compute and depends on assumptions.

The expected value: if the algorithm performs N1,N2,…,NkN_1, N_2, \dots, N_k operations with probabilities p1,p2,…,pkp_1, p_2, \dots, p_k (where p1+⋯+pk=1p_1 + \dots + p_k = 1), then E=N1p1+N2p2+⋯+Nkpk.E = N_1 p_1 + N_2 p_2 + \dots + N_k p_k .

Linear (sequential) search looks for a value xx in an array A[1..n]A[1..n] by comparing xx with A[1],A[2],…A[1], A[2], \dots until it finds xx or reaches the end. It returns the location loc, or 0 if xx is not present.

Linear search pseudocode
Algorithm LinearSearch(A[1..n], x)
loc ← 0
k ← 1
while loc = 0 and k ≤ n do
    if x = A[k] then
        loc ← k
    end if
    k ← k + 1
end while
return loc            // 0 means "x is not in A"
C · search_bug.c
#include <stdio.h>

/* The loop as printed: k = k + 1 sits INSIDE the if-block.
   A safety limit stops the demonstration after 10 rounds. */
int main(void)
{
    int A[] = {0, 42, 17, 8};   /* A[1..3] */
    int n = 3, x = 8;
    int loc = 0, k = 1, rounds = 0;

    while (loc == 0 && k <= n) {
        if (x == A[k]) {
            loc = k;
            k = k + 1;
        }
        rounds++;
        if (rounds == 10) {
            printf("still at k = %d after %d rounds: loop never ends\n", k, rounds);
            return 0;
        }
    }
    printf("found at %d\n", loc);
    return 0;
}
Output
still at k = 1 after 10 rounds: loop never ends

The corrected version, which also counts comparisons:

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

/* Linear search on A[1..n] (position 0 is not used, to match the
   1-based pseudocode). Returns loc, or 0 if x is not present.
   *comparisons receives the number of comparisons x == A[k]. */
int linear_search(const int A[], int n, int x, int *comparisons)
{
    int loc = 0;
    int k = 1;
    *comparisons = 0;
    while (loc == 0 && k <= n) {
        (*comparisons)++;
        if (x == A[k])
            loc = k;
        k = k + 1;          /* outside the if: always move to the next element */
    }
    return loc;
}

int main(void)
{
    int A[] = {0, 42, 17, 8, 99, 23};   /* A[1..5] */
    int n = 5;
    int tests[] = {42, 23, 50};
    int c;

    for (int t = 0; t < 3; t++) {
        int loc = linear_search(A, n, tests[t], &c);
        if (loc == 0)
            printf("x = %2d: not present, comparisons = %d\n", tests[t], c);
        else
            printf("x = %2d: found at location %d, comparisons = %d\n", tests[t], loc, c);
    }

    /* Average over all successful searches, each position equally likely */
    int total = 0;
    for (int i = 1; i <= n; i++) {
        linear_search(A, n, A[i], &c);
        total += c;
    }
    printf("average comparisons (successful) = %d/%d = %.1f, (n+1)/2 = %.1f\n",
           total, n, (double)total / n, (n + 1) / 2.0);
    return 0;
}
Output
x = 42: found at location 1, comparisons = 1
x = 23: found at location 5, comparisons = 5
x = 50: not present, comparisons = 5
average comparisons (successful) = 15/5 = 3.0, (n+1)/2 = 3.0

Let C(n)C(n) be the number of comparisons between xx and array elements.

  • Best case: x=A[1]x = A[1]. One comparison: Cbest(n)=1C_{\text{best}}(n) = 1.
  • Worst case: xx is the last element or not present. All nn elements are compared: Cworst(n)=nC_{\text{worst}}(n) = n.
  • Average case (assume xx is present and equally likely to be at any of the nn positions, each with probability 1n\tfrac{1}{n}):

If the search succeeds only with probability pp (Levitin, §2.1), the same method gives Cavg(n)=p(n+1)2+n(1−p)C_{\text{avg}}(n) = \dfrac{p(n+1)}{2} + n(1-p). For p=1p = 1 this is (n+1)/2(n+1)/2; for p=0p = 0 it is nn.

A first look at O, Ω and Θ

To describe growth without constant factors we use three asymptotic notations (they describe behaviour as n→∞n \to \infty). Unit 2 studies them in detail; here are the definitions you need now.

NotationMeaningFormal condition (for some constants c,c1,c2>0c, c_1, c_2 > 0 and n0n_0, for all n≥n0n \ge n_0)
f(n)=O(g(n))f(n) = O(g(n))Upper bound: ff grows at most like gg0≤f(n)≤c g(n)0 \le f(n) \le c\, g(n)
f(n)=Ω(g(n))f(n) = \Omega(g(n))Lower bound: ff grows at least like gg0≤c g(n)≤f(n)0 \le c\, g(n) \le f(n)
f(n)=Θ(g(n))f(n) = \Theta(g(n))Tight bound: ff grows exactly like ggc1g(n)≤f(n)≤c2g(n)c_1 g(n) \le f(n) \le c_2 g(n)

For example, 3n+2=Θ(n)3n + 2 = \Theta(n): take c1=3c_1 = 3, c2=4c_2 = 4, n0=2n_0 = 2, since 3n≤3n+2≤4n3n \le 3n + 2 \le 4n for all n≥2n \ge 2.

A bound and a case are different things. The case (best, worst, average) chooses which function we study; the notation (O, Ω, Θ) describes how that function grows. For linear search, Cworst(n)=n=Θ(n)C_{\text{worst}}(n) = n = \Theta(n), Cbest(n)=1=Θ(1)C_{\text{best}}(n) = 1 = \Theta(1) and Cavg(n)=(n+1)/2=Θ(n)C_{\text{avg}}(n) = (n+1)/2 = \Theta(n). Each case has its own tight bound.

Key takeaways

  • Time complexity counts key operations; space complexity counts extra memory, both as functions of nn.
  • Worst case = maximum, best case = minimum, average case = expected value over a stated input distribution.
  • Linear search: best 1, worst nn, average (n+1)/2(n+1)/2 comparisons (successful search).
  • O = upper bound, Ω = lower bound, Θ = tight bound; these are not the same as worst, best, average.

Practice questions

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

Question 1 · multiple choice

For linear search on n=9n = 9 elements, with xx present and every position equally likely, the average number of comparisons is:

Show answer

Answer: B. 5

(n + 1)/2 = (9 + 1)/2 = 5. The value 4.5 = n/2 forgets that positions are counted from 1.

Question 2 · multiple choice

What is the worst-case number of comparisons of linear search on nn elements?

Show answer

Answer: D. nn

When x is last or absent, every element is compared once. (n+1)/2 is the average case.

Question 3 · multiple choice

Which statement is correct?

Show answer

Answer: B. The best case of linear search is Θ(1)\Theta(1).

The best case makes exactly 1 comparison, a constant, so it is Θ(1). The notations describe growth of any function, not a particular case.

Question 4 · multiple choice

In the printed linear search, K=K+1 is inside the if block. What happens when x≠A[1]x \ne A[1]?

Show answer

Answer: C. The loop never ends because K stays at 1.

K only increases when x is found, so A[1] is tested forever. This breaks the finiteness property.

Question 5 · multiple choice

A search succeeds with probability p=0.5p = 0.5 on n=5n = 5 elements (positions equally likely). The average number of comparisons is:

Show answer

Answer: D. 4

p(n+1)/2 + n(1 − p) = 0.5 × 3 + 5 × 0.5 = 1.5 + 2.5 = 4. The value 3 assumes the search always succeeds.

Question 6 · short answer

Show that 5n+3=Θ(n)5n + 3 = \Theta(n) by finding constants.

Show worked answer

Lower bound: 5n ≤ 5n + 3 for all n ≥ 1, so c₁ = 5. Upper bound: 5n + 3 ≤ 6n when 3 ≤ n, so c₂ = 6 with n₀ = 3. Hence 5n ≤ 5n + 3 ≤ 6n for all n ≥ 3, and 5n + 3 = Θ(n).

↑ ↓ move↵ openTab switch type