Quicksort in Python3

Below is an example of the Quicksort algorithm in Python3. See the Quicksort page for more information and implementations.


quicksort in Python3

def quickSort(array, startIndex, endIndex):
    # verify that the start and end index have not overlapped
    if (startIndex < endIndex):
        # calculate the pivotIndex
        pivotIndex = partition(array, startIndex, endIndex)
        # sort the left sub-array
        quickSort(array, startIndex, pivotIndex)
        # sort the right sub-array
        quickSort(array, pivotIndex + 1, endIndex)

def partition(array, startIndex, endIndex):
    pivotIndex = (startIndex + endIndex) / 2
    pivotValue = array[int(pivotIndex)]

    while (True):

        # start at the FIRST index of the sub-array and increment
        # FORWARD until we find a value that is > pivotValue
        while (array[startIndex] < pivotValue): startIndex += 1

        # start at the LAST index of the sub-array and increment
        # BACKWARD until we find a value that is < pivotValue
        while (array[endIndex] > pivotValue): endIndex -= 1

        if (startIndex >= endIndex): return endIndex

        # swap values at the startIndex and endIndex
        temp = array[startIndex]
        array[startIndex] = array[endIndex]
        array[endIndex] = temp

if __name__ == '__main__':
    array = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8]
    quickSort(array, 0, len(array) - 1)
    print(array)

Discussion