简体   繁体   English

Quicksort算法Python错误

[英]Quicksort algorithm Python error

I am trying to implement Quicksort using Python. 我正在尝试使用Python实现Quicksort。 This is my code: 这是我的代码:

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()

How come when I run my code, it says that it runs into this error: 当我运行我的代码时,为什么会遇到以下错误:

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

The only problem is that you try to select randomIndex even, when lst is empty, just move your initializations into if condition where you are sure that they are non empty 唯一的问题是,即使当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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM