Search code examples
pythonalgorithmquicksort

Quicksort not sorting the lower half


I am new to programming and trying to do Udacity's quicksort practice. But my code doesn't quite do it.

Something might be wrong with how I assign low and high in the quicksort function, but I don't know how to fix it.

# this returns a sorted array
def quicksort(array):
    low = 0
    high = len(array) - 1
    if low >= high:
        return array
    pi = partition(array, low, high)
    array[:pi-1] = quicksort(array[:pi-1])
    array[pi+1:] = quicksort(array[pi+1:])
    return array

# this places the pivot in the right position in the array.
# all elements smaller than the pivot are moved to the left of it.    
def partition(array, low, high):
    border = low
    pivot = array[high]
    for i in range(low, high):
        if array[i] <= pivot:
            array[border], array[i] = array[i], array[border]
            border += 1
    array[border], array[high] = array[high], array[border]
    return border

test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)

Expected answer: [1, 3, 4, 6, 9, 14, 20, 21, 21, 25]

What I got: [1, 4, 3, 9, 6, 14, 20, 21, 21, 25]


Solution

  • To get the lower half of the array you need to do array[:pi] not array[:pi-1]. The end index is exclusive. If you change the line to:

    array[:pi] = quicksort(array[:pi])
    

    your algorithm works: repl.it link