Search code examples
pythonsortingbubble-sort

Bubble Sort Highest to Lowest (Python)


Hi could someone help me so instead of sorting from lowest to highest, sort it form highest to lowest.

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]

Solution

  • You need to change the symbol in the if condition, here is a code with the two ways (lowest to highest and highest to lowest) in your function:

    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]