You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Bubble Sort按元组第二元素实现降序排序的问题排查

代码问题修正说明

你的代码存在以下几处核心问题,导致没有按预期完成排序:

  • 语法错误:for j in range(0, len(countries)-i,-1) 行末尾缺失冒号,且range参数配置错误:设置步长为-1但起始值小于终止值,会直接生成空序列,内层循环完全没有执行,没有发生任何元素交换。
  • 逻辑错误:return 语句放在了外层for循环内部,第一轮冒泡结束就直接返回结果,即使循环参数正确也只能完成一轮排序,无法得到正确结果。
  • 冗余结构:你自定义了LinkedList链表类,但实际排序操作的是普通Python列表,完全没有用到链表结构,和你描述的「对链表进行降序排序」需求不符。
  • 循环结构错误:标准冒泡排序只需要两层循环,你写了三层for循环,逻辑完全错误。

注:你看到的「按字母顺序排列」是假象:因为排序逻辑完全没有执行,你调用reverse只是把原始输入列表倒序输出,刚好原始列表倒序后的国名顺序近似字母升序,才会产生误判。


修正后的实现

1. 普通列表冒泡排序(按元组第二个元素降序)

countries = [("Ukraine",41879904),("Brunei",442400),("Christmas Island (Australia)",1928),("Mauritius",1265985),("Lesotho",2007201),("Guatemala",16604026),("British Virgin Islands (UK)",30030),("Malta",493559),("Greenland (Denmark)",56081),("Guernsey (UK)",62792)]

def bubbleSort(countries):
    n = len(countries)
    for passnum in range(n-1, 0, -1):
        for i in range(passnum):
            # 降序排序:前一个元素数值小于后一个则交换
            if countries[i][1] < countries[i+1][1]:
                countries[i], countries[i+1] = countries[i+1], countries[i]
    return countries

print("Bubble Sort")
print("未排序列表: ", countries)
print('\n')

sorted_countries = bubbleSort(countries)
print("降序排序后列表: ", sorted_countries)

2. 链表结构冒泡排序(按数值降序)

如果你的需求是对自定义的LinkedList结构做排序,参考实现如下:

class LinkedList:
    def __init__(self, data):
        self.label = data[0][0]
        self.value = data[0][1]
        self.tail = None if (len(data) == 1) else LinkedList(data[1:])
    
    # 辅助方法:遍历输出链表内容
    def to_list(self):
        res = []
        cur = self
        while cur:
            res.append((cur.label, cur.value))
            cur = cur.tail
        return res

def bubble_sort_linked_list(head):
    if not head or not head.tail:
        return head
    swapped = True
    last_sorted = None
    while swapped:
        swapped = False
        cur = head
        while cur.tail != last_sorted:
            if cur.value < cur.tail.value:
                # 交换节点存储的内容即可,无需调整节点指针
                cur.value, cur.tail.value = cur.tail.value, cur.value
                cur.label, cur.tail.label = cur.tail.label, cur.label
                swapped = True
            cur = cur.tail
        last_sorted = cur
    return head

# 测试
countries = [("Ukraine",41879904),("Brunei",442400),("Christmas Island (Australia)",1928),("Mauritius",1265985),("Lesotho",2007201),("Guatemala",16604026),("British Virgin Islands (UK)",30030),("Malta",493559),("Greenland (Denmark)",56081),("Guernsey (UK)",62792)]
linked_list = LinkedList(countries)
print("排序前链表内容:", linked_list.to_list())
sorted_linked = bubble_sort_linked_list(linked_list)
print("排序后链表内容:", sorted_linked.to_list())

内容的提问来源于stack exchange,提问作者umaernu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 12:45:03