0

I have found the following quicksort algorithm:

function quicksort(array)
    less, equal, greater := three empty arrays
    if length(array) > 1  
        pivot := select any element of array
        for each x in array
            if x < pivot then add x to less
            if x = pivot then add x to equal
            if x > pivot then add x to greater
        quicksort(less)
        quicksort(greater)
        array := concatenate(less, equal, greater)

and I want to make its algorithm analysis by finding the recurrence relation. For what I see everytime that this algorithm is called, by choosing the pivot, for example, in the first position of the original array. It calls the quicksort again with the two generated lists, so I will have:

                   one list ------ pow(2,0)=1
                less       greater--------2 lists----pow(2,1)=2
   less greater              less greater-------4 lists---pow(2,2)=4

so it seems it forms a sort of binary tree, so if I get the pattern it will be: 2^k=n, where k is the levels of recursion, so I will have O(log n)

but how to do the same with analysis of recurrences? I mean, because I am not calculating the process of the de-stack of the function, something that happens in all recursive algorithms.

Any help? Thanks

2 Answers 2

1

First of all you should consider Quicksort is not deterministic. So you should make an analysis for the worst case - best case - average case.

In the worst case as an example:

T(n) = T(n-1) + O(n)

The O(n) comes from the fact that you are partitioning the whole array. The T(n-1) instead is the number of elements left to partition in the worst case.

If you solve the recurrence using the master theorem you'll get O(n^2)

Similarly in the best case:

T(n) = 2T(n/2) + O(n)

This is the same as merge-sort and again applying the master theorem you get O(nlogn).

Sign up to request clarification or add additional context in comments.

1 Comment

Can you please elaborate with the master theorem on how are you able to get O(n^2) complexity?
0

I think it's the master theorem you are looking for.

And here is an analysis of quicksort using that theorem: https://stackoverflow.com/a/40308659/2534472

1 Comment

@Prasanna done. I linked another SO answer now, that is very unlikely to be removed in the future. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.