1

This is the pseudocode I used:

enter image description here

Their calculation seems to be different from mine. Can someone explain how they derived it? Here is mine in comparison:

  • Line 1: $c_1 \cdot (n-1)$
  • Line 2: $c_2 \cdot (n-1)$
  • Line 3: $c_3 \cdot n $
  • Lines 5-6: $c_4 \cdot \frac{n(n-1)}{2}$ (the if statement executes with an arithmetic progression)
  • Line 9: $c_5 \cdot n$

Altogether,

$$T(n) = c_1(n-1) + c_2(n-1) + c_3n + c_4 \frac{n(n-1)}{2} + c_5n,$$

which simplifies to

$$ T(n) = \frac{c_4}{2} n^2 + c_1n + c_2n + c_3n - \frac{c_4}{2} n + c_5n - c_1 - c_2. $$

Yuval Filmus
  • 280,205
  • 27
  • 317
  • 514
Bee
  • 185
  • 2
  • 10

1 Answers1

0

Both of you get the same result, $\Theta(n^2)$.

Your calculation is more detailed, and takes into account all parts of the code. In contrast, the calculation in the textbook only considers the most significant part of the code (time-wise), and counts the number of iterations rather than the running time.

If I were writing the textbook, I would rephrase this sentence along the following lines:

The running time of selection sort is dominated by the inner loop (5–7), which runs $\frac{n(n-1)}{2}$ times. The total running time is proportional to that, and so it is $\Theta(n^2)$.

There is no need to carry the various constants as you do. The correct way to simplify your original formula is to state that $T(n) = \Theta(n^2)$, since you can't say anything more about the constants $c_1,\ldots,c_5$ anyway.

Yuval Filmus
  • 280,205
  • 27
  • 317
  • 514