+1 vote
116 views

# How much time it will take to sort n numbers by quicksort if some arbitrary algorithm takes (n2) time to choose pivot?

| 116 views
0
$O(n^3)$ ?
0

@shashin $T(n)=T(n-1)+O(n^2)$ right ?

0
Yessir.

$T(n) = T(n-1) + O(n) + O(n^2)$ to be precise, but you can take $T(n) = T(n-1) + O(n^2)$ without loss of generality.
0
Yeah, the answer O(n^3) is but I'm not able to understand it.
0
Just solve the recurrence relation in the above comments by any method you know. You'll get it .
0

@shashin i didn't get what $O(n)$ is for. Could u explain ?

+3

@pranay562

The intention of such questions is to test your knowledge of the working of the algorithm itself. Think about the steps in the quicksort algorithm and how they work in this example:

1. Pick a pivot. In normal quicksort, this takes $O(1)$ (just pick a random element, or the first/last). But here they've mentioned picking the pivot takes $O(n^2)$
2. Partition - this takes $O(n)$
3. Divide - in worst case the array is divided into $n - 1$ and $1$ element sub-arrays.

Put them all together to form a recurrence relation.

For regular quicksort : $T(n) = O(1) + O(n) + T(n-1)$

For this quicksort : $T(n) = O(n^2) + O(n) + T(n-1)$

Hope that helped..

0
lol ya. I missed the whole partition thing. i was focusing on " choosing pivot " part. thanks man
0

Is this the right way to solve it

$T(n)=T\left ( n-1 \right ) + n^2$

$T\left ( n \right ) = T\left (n-2 \right ) + \left ( n-2 \right )^2 + n^2$

$= T\left (n-3 \right ) + \left ( n-2 \right )^2 +\left ( n-1 \right )^2 + n^2$

and in general we will have

$T\left ( n \right )= T\left (n-k \right ) + \left ( n-k+1 \right )^2 +\left ( n-k+2 \right )^2 +....................\left ( n-1 \right )^2 + n^2.$

Now if we have k = n  then ,

$T\left ( n \right )= T\left (0 \right ) + \left ( 1 \right )^2 +\left ( 2 \right )^2 +....................\left ( n-1 \right )^2 + n^2.$

$T\left ( n \right )= n(n+)(n+2)/6$

Solving this we get

$T(n)= O(n^3)$

0
Yup - exactly how I did it. With enough practice and confidence, you can stop the moment you see the sum of a series of squares and claim it is $O(n^3)$