Search code examples
pythonsortingoperatorsbubble-sort

How can I alter my program to sort a list into descending order by changing ONE operator?


So I have this bubble sort algorithm that only worked in ascending order, so I am trying to adapt the program by passing 'ascending' or 'descending' as a parameter to the function which will change the operator from '>' to '<' when comparing adjacent items in a list. I have tried this, does anyone have any ideas? I would like to keep the code as it is and try and not to add an if statement that repeats the entire code for each condition.

array=[5,7,0,4,3,24,-1,83,2,1]

def BubbleSort(alist, order):
    position=0
    swapmade=True
    if order == 'ascending':
        symbol = '>'
    elif order == 'descending':
        symbol = '<'
    while swapmade == True:
        swapmade=False
        for count in range(len(alist)-1):
            LB=alist[position]
            UB=alist[position+1]
            if alist[position] + symbol + alist[position+1]:
                LB,UB=UB,LB
                alist.remove(alist[position+1])
                alist.insert(position, LB)
                swapmade=True
            position=position+1
            if position+1 == len(alist):
                position=0
    return alist

result = BubbleSort(array, 'ascending')
print(*result)

Solution

  • Since you wanted to keep the code you had, you can use the operator module to map an operator to a variable.

    So instead of setting symbol to "<" or ">", you could do this (where gt is greater than and lt is less than)

    import operator
    if order == 'ascending':
        op = operator.gt
    elif order == 'descending':
        op = operator.lt
    

    and this

    if op(alist[position], alist[position + 1]):
        LB, UB = UB, LB
        alist.remove(alist[position + 1])
        alist.insert(position, LB)
        swapmade = True