简体   繁体   English

冒泡排序在python中排序不正确

[英]Bubble sort not sorting properly in python

I'm making bubble sort in Python but have no idea why it doesn't sort properly.我正在 Python 中进行冒泡排序,但不知道为什么排序不正确。

N = [80000, 20, 40 , 50, 10000, 50, 60, 90, 100, 5000, 22]
for i in range(len(N)-1):
    for j in range(len(N)-i-1):
        if(N[i] > N[i+1]):
            N[i], N[i+1] = N[i+1], N[i]
print(N)

This is result of this code这是这段代码的结果

[20, 40, 50, 10000, 50, 60, 90, 100, 5000, 22, 80000]

You should use 'j' instead of 'i' in the body of the second loop.您应该在第二个循环的主体中使用 'j' 而不是 'i'。 Otherwise it is pointless to have both loops.否则两个循环都是没有意义的。 Only the outer loop is effectively executed.只有外循环被有效执行。

You should compare N[j] with N[j+1] , because you need repeatedly swapping the adjacent elements if they are in wrong order.您应该将N[j]N[j+1] ,因为如果相邻elements顺序错误,则需要重复交换相邻elements

N = [80000, 20, 40 , 50, 10000, 50, 60, 90, 100, 5000, 22]
for i in range(len(N)-1):
    for j in range(len(N)-i-1):
        if(N[j] > N[j+1]):
            N[j], N[j+1] = N[j+1], N[j]
print(N)

Output输出

[20, 22, 40, 50, 50, 60, 90, 100, 5000, 10000, 80000]

I believe you mixed up your indices i and j.我相信您混淆了索引 i 和 j。 It should read:它应该是:

N = [80000, 20, 40 , 50, 10000, 50, 60, 90, 100, 5000, 22]
for i in range(len(N)-1):
for j in range(len(N)-i-1):
    if(N[j] > N[j+1]):
        N[j], N[j+1] = N[j+1], N[j]
print(N)

Output:输出:

[20, 22, 40, 50, 50, 60, 90, 100, 5000, 10000, 80000]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM