【问题标题】:Bubble Sort Highest to Lowest (Python)冒泡排序从高到低(Python)
【发布时间】:2021-07-16 05:39:12
【问题描述】:

您好,有人可以帮我,而不是从最低到最高排序,而是从最高到最低排序。

def sort_list(to_short):
    for i in range(len(to_short)):
        for j in range(len(to_short) - 1):
            if to_short[j] < to_short[j + 1]:
                to_short[j], to_short[j + 1] = to_short[j + 1], to_short[j]

【问题讨论】:

  • 如果将“小于”符号更改为“大于”符号会怎样?

标签: python sorting bubble-sort


【解决方案1】:

您需要更改 if 条件中的符号,这是您的函数中具有两种方式(最低到最高和最高到最低)的代码:

def inplace_bubble_sort(to_sort, lower_first=True):
    for i in range(len(to_sort)):
        for j in range(len(to_sort) - 1):
            if lower_first:
                sort_condition = to_sort[j] > to_sort[j + 1]
            else:
                sort_condition = to_sort[j] < to_sort[j + 1]
            if sort_condition:
                to_sort[j], to_sort[j + 1] = to_sort[j + 1], to_sort[j]


a = [3, 4, 2, 31, 6, 1]
inplace_bubble_sort(a)
print(a)
inplace_bubble_sort(a, lower_first=False)
print(a)

result: 
first print -> [1, 2, 3, 4, 6, 31] 
second print -> [31, 6, 4, 3, 2, 1]

【讨论】:

    猜你喜欢
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 2021-12-11
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多