Quick Sort worst case, why $n^2$

algorithmsproof-explanationrecursive algorithms

I have a very hard time understanding this proof:

$$T(N) = T(N-1)+cN$$

$$T(N-1) = T(N-2)+c(N-1)$$

$$T(N-2) = T(N-3)+c(N-2)$$

$$\vdots$$

$$T(2) = T(1)+c(2)$$

$$T(N) = T(1)+c\sum_{i = 2}^{N} i = O\big(N^2\big)$$

I can see that we have $T(N-1)$ and then $T(N-2)$ and so forth because the array to check shrinks by one each time. The $cN$ is what exactly? Why does it get decremented by one, two etc.?
And how does the summation equal $n^2$ at the end, it doesn't make any sense to me. I see nowhere that $n$ is getting multiplied by itself sinse it results in $n^2$.

Best Answer

the $ck$ is the additional complexity you get by adding another element you need to sort. For example, as soon as you "sorted" 1 object, you just need to add the complexity for $N-1$, hence $T(k)=T(k-1) + ck$ where c is some constant. the $k$ on the righthand side comes from sorting the $k$'th additional input, which has complexity $k$, (since it needs to be shuffled all through the sequence in the worst case).

Hence you arrive on the bottom formula including the sum $\sum_{i=1}^N ci$. This is, by the formula for arithmetic series: $$\sum_{i=1}^N ci= cN(N+1)/2=cN^2/2 + cN/2$$ hence we get as complexity $O(N^2)$.

Related Question