Search code examples
pythonpython-3.xquicksort

How to make the following quicksort more 'pythonic'


I just implemented Quicksort in python-3 and the following is a excerpt for the swapping mechanism involved in each sub array.

Now, I can't help but notice that it looks an awful lot like a C-based loop. Which makes sense since I'm coming over from a long time of C++ development. I was wondering if this loop can be made more pythonic.

I tried using for items in array but that's not helpful since the iterator should not increase for every round of the loop.

Any suggestions are appreciated!

#  last elem is pivot at start
pivPos = end
#  iterate the list and bring pivot to correct position
count = 0

while (count != pivPos):

    #  swap places with elem just before pivot
    if arr[count] >= arr[pivPos]:
        temp = arr[count]
        arr[count] = arr[pivPos - 1]
        arr[pivPos - 1] = temp

        #  now swap the pivot
        arr[pivPos - 1] = arr[pivPos]
        arr[pivPos] = temp

        #  update pivPos
        pivPos -= 1

    else:
        count += 1
        continue

Solution

  • This part:

    temp = arr[count]
    arr[count] = arr[pivPos - 1]
    arr[pivPos - 1] = temp
    arr[pivPos - 1] = arr[pivPos]
    arr[pivPos] = temp
    

    can be written without temp like this:

    arr[count], arr[pivPos-1], arr[pivPos] = arr[pivPos-1], arr[pivPos], arr[count]
    

    Also continue is redundant, you can remove it and the code will behave the same.

    However the real pythonic way is:

    arr.sort()
    

    full edited code easy reference:

    pivPos = end
    count = 0
    while count != pivPos:
        if arr[count] >= arr[pivPos]:
            arr[count], arr[pivPos-1], arr[pivPos] = arr[pivPos-1], arr[pivPos], arr[count]
            pivPos -= 1
        else:
            count += 1