获取 bubblesort 的索引和值 python

get index and value of bubblesort python

我实现了冒泡排序来对数字列表进行排序,我尝试使用枚举来获取索引和值,但由于某些原因不起作用。我期待类似 [(index, value)] 的东西,但输出也可以不同,只要我能看到带有值部分的索引。
结果 [(4, 25), (2, 30), (3, 31), (1, 33), (0,38)].
希望有一个简单的改变。

def sortPercent(unsortedArr):
    n = len(unsortedArr)
    for i, percent in enumerate(range(n-1)):        
        for j, percent in enumerate(range(0, n-i-1)):        
            if unsortedArr[j] > unsortedArr[j + 1]:
                unsortedArr[j],unsortedArr[j+1] = unsortedArr[j+1], unsortedArr[j]
    return unsortedArr

if __name__ == "__main__":
    unsortedArr = [38, 33, 30, 31, 25]
    print(sortPercent(unsortedArr))

您根本不必使用 enumerate(),此函数定义可以满足您的需求,代码简单:

def sortPercent(unsortedArr):
    n = len(unsortedArr)
    unsortedArr = [(i, unsortedArr[i]) for i in range(n)]
    for i in range(n-1):        
        for j in range(0, n-i-1):        
            if unsortedArr[j][1] > unsortedArr[j + 1][1]:
                unsortedArr[j],unsortedArr[j+1] = unsortedArr[j+1], unsortedArr[j]
    return unsortedArr

你必须对未排序的 arr 使用枚举

def sortPercent(unsortedArr):
    unsortedArr = list(enumerate(unsortedArr)) # [(0, 38), (1, 33), (2, 30), (3, 31), (4, 25)]
    n = len(unsortedArr)
    for i, percent in enumerate(range(n-1)):        
        for j, percent in enumerate(range(0, n-i-1)):        
            if unsortedArr[j][1] > unsortedArr[j + 1][1]: # when j = 0, unsortedArr[j] = (0,38), unsortedArr[j][1] = 38, unsortedArr[j+1][1]=30
                unsortedArr[j],unsortedArr[j+1] = unsortedArr[j+1], unsortedArr[j]
    return unsortedArr


unsortedArr = [38, 33, 30, 31, 25]
print(sortPercent(unsortedArr))
# [(4, 25), (2, 30), (3, 31), (1, 33), (0, 38)]
def sortPercent(unsortedArr):
    n = len(unsortedArr)

    for i, percent in enumerate(range(n-1)):        
        for j, percent in enumerate(range(0, n-i-1)):        
            if unsortedArr[j] > unsortedArr[j + 1]:
                unsortedArr[j],unsortedArr[j+1] = unsortedArr[j+1], unsortedArr[j]

    return unsortedArr

if __name__ == "__main__":

    unsortedArr = [38, 33, 30, 31, 25]

    sortedArr=sortPercent(unsortedArr.copy())
    for i in range (len(unsortedArr)):
         print(sortedArr[i],"-",unsortedArr.index(sortedArr[i]))