Quicksort算法Python错误

时间:2016-01-31 19:01:48

标签: python quicksort

我正在尝试使用Python实现Quicksort。 这是我的代码:

import random

def quickSort(lst):
    randomIndex = random.randint(0,len(lst)-1)
    pivot = lst[randomIndex]
    greater = []
    less = []
    equal = []
    if len(lst) > 1:
        for num in lst:
            if num > pivot:
                greater.append(num)
            elif num == pivot:
                equal.append(num)
            else:
                less.append(num)
        return quickSort(less)+equal+quickSort(greater)
    else:
        return lst

def main():
    lst = [1000000,100000,1000,10000,100,10]
    sortedLst = quickSort(lst)
    print("Quicksorted List: ", sortedLst)

main()

为什么我运行我的代码,它说它遇到了这个错误:

ValueError: empty range for randrange() (0,0, 0)

1 个答案:

答案 0 :(得分:2)

唯一的问题是,即使lst为空,您也尝试选择randomIndex,只需将初始化移至if条件,即可确定它们是非空的

import random

def quickSort(lst):
    if len(lst) > 1:
        randomIndex = random.randint(0,len(lst)-1)
        pivot = lst[randomIndex]
        greater = []
        less = []
        equal = []
        for num in lst:
            if num > pivot:
                greater.append(num)
            elif num == pivot:
                equal.append(num)
            else:
                less.append(num)
        return quickSort(less)+equal+quickSort(greater)
    else:
        return lst

def main():
    lst = [1000000,100000,1000,10000,100,10]
    sortedLst = quickSort(lst)
    print("Quicksorted List: ", sortedLst)

main()