Python 快速排序实现遗漏了重复元素

标签 python sorting python-2.7 quicksort

我正在用 Python 实现快速排序。我的代码成功地对列表进行排序,但未能包含重复元素。请帮我找出错误。

from random import choice

def quickSort(lst):
    if not lst:
        return []
    else:
        pivot = choice(lst)
        lesser = quickSort([l for l in lst if l < pivot])
        greater = quickSort([l for l in lst if l > pivot])
        #print lesser, pivot, greater
        return lesser + [pivot] + greater

print quickSort([3, 2, 5, 6, 1, 7, 2, 4,234, 234, 23, 1234, 24, 132])

输出:

[1, 2, 3, 4, 5, 6, 7, 23, 24, 132, 234, 1234]

最佳答案

你的条件之一需要是<=>= (但不是两者)。

否则,您最终会选择一个重复元素作为基准,并且由于其他副本既不大于也不小于基准,因此它们不会传递给 lesser 中的任何一个。或 greater排序。

但是,由于您没有为您的项目使用唯一标识符,因此在您使用整数的示例中,这也将涉及将您的枢轴包含在集合中。为了避免这种情况,您可能需要为数据透视选择一个索引而不是一个

例如:

from random import randint

def quickSort(lst):
    if not lst:
        return []
    else:
        pivot = randint(0, len(lst) - 1)
        pivot_value = lst[pivot]
        lesser = quickSort([l for i,l in enumerate(lst)
                           if l <= pivot_value and i != pivot])
        greater = quickSort([l for l in lst if l > pivot_value])
        return lesser + [pivot_value] + greater

测试:

>>> from random import randint
>>>
>>> def quickSort(lst):
...     if not lst:
...         return []
...     else:
...         pivot = randint(0, len(lst) - 1)
...         pivot_value = lst[pivot]
...         lesser = quickSort([l for i,l in enumerate(lst)
...                            if l <= pivot_value and i != pivot])
...         greater = quickSort([l for l in lst if l > pivot_value])
...         return lesser + [pivot_value] + greater
...
>>> print quickSort([3, 2, 5, 6, 1, 7, 2, 4,234, 234, 23, 1234, 24, 132])
[1, 2, 2, 3, 4, 5, 6, 7, 23, 24, 132, 234, 234, 1234]

关于Python 快速排序实现遗漏了重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15516147/

相关文章:

Python 说我向我的函数传递了太多参数?

python - 是否可以在 python 中创建图排列?

python - 如何在多索引数据框中选择第一级最后一个键中的行?

python - ModelForm 使用的 request.POST 前缀不适用于单元测试中的 client.post

java 。如何将两个最初排序的队列合并到一个队列中? (没有链表或其他东西)

MATLAB 按自定义条件排序

algorithm - 短冒泡和冒泡排序的实现

mysql - 使用 Python 从我的机器访问单独的 MySQL 服务器 - 如何? [Mac OS X]

python - Tkinter 列表框

python SimpleHTTPRequestHandler 服务器在退出后将套接字留在 TIME_WAIT 状态