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
  • 276,994
  • 27
  • 311
  • 503
Bee
  • 185
  • 1
  • 9
  • We discourage "please check whether my answer is correct" questions, as only "yes/no" answers are possible, which won't help you or future visitors. See here and here. Can you edit your post to ask about a specific conceptual issue you're uncertain about? As a rule of thumb, a good conceptual question should be useful even to someone who isn't looking at the problem you happen to be working on. If you just need someone to check your work, you might seek out a friend, classmate, or teacher. – D.W. Apr 23 '21 at 04:23
  • See https://cs.stackexchange.com/q/23593/755 for the general techniques – D.W. Apr 23 '21 at 04:24

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
  • 276,994
  • 27
  • 311
  • 503