简体   繁体   中英

Quicksort algorithm Python error

I am trying to implement Quicksort using Python. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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