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

In-place quicksort algorithm in Python 2

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

Problem

I have tried to implement an in-place quicksort Algorithm in Python 2. Please suggest how I can

  • Make the code more efficient



  • Increase readability



  • Improve writing style



  • Make it more Pythonic



def swap(x,y):
    return y,x

def sort(ar, start, end, l):

    if startp:
                        ind=j
                        ar[i],ar[j] = swap(ar[i],ar[j])
                        break

        #Swap pivot with the first bigger-than-pivot number            
        ar[ind+1], ar[end-1] = swap(ar[ind+1], p)

        ar = sort(ar, start, ind+1, l)
        ar = sort(ar, ind+2, end, l)

        return ar

    else:
        return ar

Solution

Your swap function is pointless. It would be far more clear just to switch the order directly in the right hand side of every assignation.

Also, in the second for loop. I'm not sure you're supposed to iterate from 0. At best it should be from start. Remember, the idea of quicksort is that you only modify the part of the array that corresponds to the function, [start, end) in this case. However, with that loop, you're now making O(n^2) iterations, which can be improved like this:

p = ar[end-1]
idx_le = start
idx_gt = end-2
while idx_le <= idx_gt:
    if ar[idx_le] <= p:
        idx_le += 1
    else:
        ar[idx_gt], ar[idx_le] = ar[idx_le], ar[idx_gt]
        idx_gt -= 1

ar[idx_le], ar[end-1] = ar[end-1], ar[idx_le]
return ar


The main idea is to keep track where the elements less than p should be placed, same with the elements greater than p. The new recursion should be [start, idx_le) [idx_le+1, end).

Code Snippets

p = ar[end-1]
idx_le = start
idx_gt = end-2
while idx_le <= idx_gt:
    if ar[idx_le] <= p:
        idx_le += 1
    else:
        ar[idx_gt], ar[idx_le] = ar[idx_le], ar[idx_gt]
        idx_gt -= 1

ar[idx_le], ar[end-1] = ar[end-1], ar[idx_le]
return ar

Context

StackExchange Code Review Q#75142, answer score: 3

Revisions (0)

No revisions yet.