Tianyu Jiang
Tianyu Jiang

Reputation: 53

Something wrong with my quick sort Python code?

I meet a issue with my quick sort code.

class Sort:
    def quickSort(self, unsortedlist):
        if len(unsortedlist) <= 1:
            return unsortedlist
        pivot = unsortedlist[0]
        unsortedlist.remove(unsortedlist[0])
        left, right = [], []
        for num in unsortedlist:
            if num < pivot:
                left.append(num)
            else:
                right.append(num)
        return self.quickSort(left) + [pivot] + self.quickSort(right)


if __name__ == "__main__":
    a = [76, 76, 65, 72, 58, 64, 82, 3, 22, 31]
    print(Sort().quickSort(a))
    print(Sort().quickSort(a))
    print(Sort().quickSort(a))

The result will be:

[3, 22, 31, 58, 64, 65, 72, 76, 76, 82]
[3, 22, 31, 58, 64, 65, 72, 76, 82]
[3, 22, 31, 58, 64, 65, 72, 82]

Why the sorted list become less and less?

Upvotes: 1

Views: 150

Answers (1)

Masklinn
Masklinn

Reputation: 42272

unsortedlist.remove(unsortedlist[0])

So every time you call quickSort on a list you remove the first element from the source list.

It doesn't really matter for the recursive calls because you "control" the list, but for the "top-level" calls after every call to quickSort you've "lost" one of the elements.

Upvotes: 3

Related Questions