为什么我的快速排序有时会错过一对数字?

发布于 2025-02-08 19:11:19 字数 631 浏览 0 评论 0原文

我做了我自己的快速排序算法,并且效果很好,期望每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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挖鼻大婶 2025-02-15 19:11:19

据我所知,快速排序算法要求您使用递归,一旦选择一个枢轴,就将算法应用于每种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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文