为什么我的快速排序有时会错过一对数字?
我做了我自己的快速排序算法,并且效果很好,期望每3或4秒,它会错过一对数字,最终列表仍然没有分数。
例如,它不是[1、2、3、4、5、6],而是[1、2、3, 5、4, 6]
这是我的代码
for i in range(len(lista)):
pivot = random.choice(lista)
for j in range(len(lista)):
if lista[j]>pivot and lista.index(lista[j])<lista.index(pivot):
lista[lista.index(pivot)] = lista[j]
lista[j] = pivot
elif lista[j]<pivot and lista.index(lista[j])>lista.index(pivot):
lista[lista.index(pivot)] = lista[j]
lista[j] = pivot
else:
j = j
我不知道问题是什么,甚至可以在
帮助
ive made my own quick sort algorithm and it works fairly well, expect every 3 or 4 sorts, it misses a pair of numbers and the final list remains to be unsorted.
for example, instead of the list being [1, 2, 3, 4, 5, 6], it'll be [1, 2, 3, 5, 4, 6]
this is my code
for i in range(len(lista)):
pivot = random.choice(lista)
for j in range(len(lista)):
if lista[j]>pivot and lista.index(lista[j])<lista.index(pivot):
lista[lista.index(pivot)] = lista[j]
lista[j] = pivot
elif lista[j]<pivot and lista.index(lista[j])>lista.index(pivot):
lista[lista.index(pivot)] = lista[j]
lista[j] = pivot
else:
j = j
i dont know what the issue might be, even visualizing the code in python tutor doesnt help because in the first pivot selection, it always picks the same pivots
help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,快速排序算法要求您使用递归,一旦选择一个枢轴,就将算法应用于每种sublist中的算法。
在您拥有的示例中,您正在为列表的每个项目随机选择一个枢轴,如果最后您选择了一次(或者也许大多数,我不确定),则可以对列表进行排序。但是,由于您是随机选择它们,因此有时选择的枢轴不足以正确订购列表。
As far as I know the quick sort algorithm requires you to use recursion, to apply the algorithm in each sublist created once you choose a pivot.
In the example that you have you are choosing a pivot randomly for each item of the list, it could sort the list if at the end you have chosen all items at least once (or maybe the majority of them, I am not sure), but since you are choosing them randomly it is probably that sometimes the pivots chosen are not enough to order the list properly.