0

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)
2
  • error is pretty self-explonatory. You call random on empty range, thus at some point your code calls quicksort([]), and you try to get randomIndex/pivot even when the list is empty Commented Jan 31, 2016 at 19:05
  • It's most likely because either greater or less has one element in them. So when you set randomIndex to be a range from 0 to the length of the list, you get random.randint(0, 0). I'd recommend adding a print command before your return statement to see what those lists look like. Commented Jan 31, 2016 at 19:05

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.