Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm currently doing an algorithms course and implemented this version of the quicksort algorithm. I would like to know if it is an efficient implementation. I've seen a couple others where there is a partition function that partitions the list is that a superior method to what I did?

def quickSort(aList):
    first = []
    second = []
    size = len(aList)
    if size ==0:
        return []
    elif size == 1:
        return aList
    elif size ==2:
        if(aList[1]<aList[0]):
            return list([aList[1],aList[0]])
        else:
            return aList
    else:
        key = aList[0]
        for i in range(1,size):
            if aList[i]<key:
                first.append(aList[i])
            else:
                second.append(aList[i])
        first.append(key)
    return quickSort(first) + quickSort(second)
share|improve this question

1 Answer 1

You've implemented a very basic version of the Quicksort algorithm, where you choose the first element as pivot element.

The running time of the quicksort algorithm is however very dependent on the quality of the pivot element. (The pivot should try to split the problem in equal problems). Making it fixed isn't really useful.

For example: say you want to run quicksort on an already sorted list. If you keep using the first element as pivot element, you will end up with a quadratic running time.

A 'solution' is to use random pivot elements, where in each recursive call you choose the pivot randomly (each element has an equal chance). You can find more on this approach online. But the idea is to end up with an average running time of \$O(n*log(n))\$

In addition you implement it by creating 2 new lists and merging them together. Quicksort normally has the advantage that everything can happen in-place, which is a great advantage memory wise.

share|improve this answer
1  
You're right I should have thought this through a bit more thanks for the response. –  imakeApps Mar 22 at 11:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.