带有交换计数的 Python 冒泡排序列表

New*_*bie 4 python sorting

我正在尝试创建一个函数,该函数使用冒泡排序对列表进行排序,并返回一个包含交换和比较次数的元组。这样:

print(perform_bubble_sort([3, 5, 7]))    
>>> (3, 0)
Run Code Online (Sandbox Code Playgroud)

.
我尝试使用以下代码,但由于某种原因它没有返回正确的比较次数。

def perform_bubble_sort(blist):
    cmpcount, swapcount = 0, 0
    while True:
        swapped = False
        for i in range(1, len(blist)):
            cmpcount += 1
            if blist[i-1] > blist[i]:
                swapcount += 1
                blist[i-1], blist[i] = blist[i], blist[i-1]
                swapped = True
        if not swapped:
            break
    return cmpcount, swapcount
Run Code Online (Sandbox Code Playgroud)

lai*_*e9m 7

def perform_bubble_sort(blist):
    cmpcount, swapcount = 0, 0
    for j in range(len(blist)):
        for i in range(1, len(blist)-j):
            cmpcount += 1
            if blist[i-1] > blist[i]:
                swapcount += 1
                blist[i-1], blist[i] = blist[i], blist[i-1]
    return cmpcount, swapcount
Run Code Online (Sandbox Code Playgroud)

你不需要blist每次都迭代