我的代码中执行快速排序的错误在哪里?

时间:2019-03-26 09:40:00

标签: python python-3.x quicksort

我已经编写了一些python代码来实现quicksort算法。 与其他代码相比,没有区别。

但是,某些列表的输出没有变化(根本没有排序)。 我找不到毛病。

# Quick sort algorithm

#func. to devide the array for one given pivot
def part_by_pivot(array, left, right, pivot): 

    leftindex = left #initial index of given array
    rightindex = right - 1 #'right' is the size of given array

    while True:
        #finding left value less than the pivot
        for i in range(len(array)):
            if array[leftindex] < pivot:
                leftindex += i
                break

        #finding left value less than the pivot
        for i in range(len(array)): 
            if array[rightindex] > pivot and rightindex > 0:
                rightindex -= i
                break

        if leftindex > rightindex:
            leftindex, rightindex = rightindex, leftindex
        else:
            break

    #pivot swapped
    leftindex, right = right, leftindex

    return leftindex


#func. to do quick sort method
def quicksort(array, left, right):

    #base case
    if right-left <= 0:
        return

    #recursive call
    else:
        pivot = array[right-1]
        partitionPoint = part_by_pivot(array, left,right-1,pivot)
        quicksort(array, left, partitionPoint-1)
        quicksort(array, partitionPoint+1, right-1)

alist = [54,26,93,17,77,31,44,55,20]
quicksort(alist, 0, len(alist))
print(alist)

0 个答案:

没有答案