【问题标题】:Python Bubble Sort list with swap count带有交换计数的 Python 冒泡排序列表
【发布时间】:2018-07-03 23:46:23
【问题描述】:

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

print(perform_bubble_sort([3, 5, 7]))    
>>> (3, 0)

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

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

【问题讨论】:

    标签: python sorting


    【解决方案1】:
    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
    

    您不需要每次都遍历blist

    【讨论】:

    • 行得通!当所有项目都排序后,如何让这个函数停止执行?
    • @Newbie 你可以像这样使用swapped。我删除它是因为通常人们不会在冒泡排序中这样做。
    【解决方案2】:
    def queue(lst):
        n = len(lst)
        swipe_count = 0
    
        for i in range(n):
            for j in range(n - i - 1):
                if lst[j] > lst[j + 1]:
                    lst[j], lst[j + 1] = lst[j + 1], lst[j]
                    swipe_count += 1
    
        return lst, swipe_count
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 2012-07-05
      • 2021-02-06
      • 1970-01-01
      • 2012-07-14
      相关资源
      最近更新 更多