HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonMinor

Pythonic quicksort algorithm

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pythonicalgorithmquicksort

Problem

Is my implementation of quicksort efficient, in-place, pythonic ?

def quicksort(array, lo, hi):
    if hi - lo < 2:
        return
    key = random.randrange(lo, hi)
    array[key], array[lo] = array[lo], array[key]
    y = 1 + lo
    for x in xrange(lo + 1, hi):
        if array[x] <= array[lo]:
            array[x], array[y] = array[y], array[x]
            y += 1
    array[lo], array[y - 1] = array[y - 1], array[lo]
    quicksort(array, lo, y - 1)
    quicksort(array, y, hi)

a = map(int, raw_input().split())
quicksort(a, 0, len(a))

Solution

Looks good in general. Few comments.

-
Missing import random.

-
Random pivot selection is just one of many possible strategies. It may or may not be a good strategy depending on the nature of data. Only the client knows what a suitable strategy will be; let him chose.

-
No Raw Loops mantra: Every loop possible represents an algorithm, often very important itself. In this case the algorithm is partition. It is worthy to be factored out in a function of its own.

Context

StackExchange Code Review Q#63764, answer score: 3

Revisions (0)

No revisions yet.