为什么我的气泡排序无法正常工作?

时间:2020-02-15 10:12:29

标签: python sorting bubble-sort

我一直在尝试创建BubbleSort来整理数组。数组的名称为UserNameArray,数组的格式为。是一个由六个字符组成的数字字符串,而是一个字符串。例如:123456James。

我的程序整理出一些数据,但是它无法运行几次才能真正整理出所有数据。

UserNameArray = ["234511Jack","734636Dan","237894Daniel", "124119James", "000001Test","999999Donald"]
def BubbleSort():
    for i in range(0,len(UserNameArray)-1):
        for j in range(0,i):
            UserID = int(UserNameArray[j][0:5])
            UserIDNext = int(UserNameArray[j+1][0:5])
            print(i,j)
            print(UserID,UserIDNext)
            if UserIDNext < UserID:
                store = UserNameArray[j]
                UserNameArray[j] = UserNameArray[j+1]
                UserNameArray[j+1] = store
            print(UserNameArray)
BubbleSort()

谢谢。

2 个答案:

答案 0 :(得分:0)

尝试一下:

UserNameArray = ["234511Jack","734636Dan","237894Daniel", "124119James", "000001Test","999999Donald"]
def BubbleSort():
    for i in range(len(UserNameArray)-1,0,-1): // you use wrong direction here
        for j in range(0,i):
            UserID = int(UserNameArray[j][0:5])
            UserIDNext = int(UserNameArray[j+1][0:5])
            print(i,j)
            print(UserID,UserIDNext)
            if UserIDNext < UserID:
                store = UserNameArray[j]
                UserNameArray[j] = UserNameArray[j+1]
                UserNameArray[j+1] = store
            print(UserNameArray)
BubbleSort()

答案 1 :(得分:-1)

UserNameArray = [
    "234511Jack",
    "734636Dan",
    "237894Daniel", 
    "124119James", 
    "000001Test",
    "999999Donald"
]
def BubbleSort():
    for i in range(0,len(UserNameArray)-1):
        for j in range(0,len(UserNameArray)-1-i):
            UserID = int(UserNameArray[j][0:5])
            UserIDNext = int(UserNameArray[j+1][0:5])
            if UserIDNext < UserID:
                store = UserNameArray[j]
                UserNameArray[j] = UserNameArray[j+1]
                UserNameArray[j+1] = store

BubbleSort()
print(UserNameArray)

!对于范围(0,len(UserNameArray)-1-i)中的j: