简体   繁体   中英

Is there a way to rewrite the if statements to avoid repeating those 2 lines of code?

I wrote insertion_sort function and added an if statement to choose if I want to order de array in ascendent or descendent mode. As you can see in the following code inside the if statements there are 2 lines of code repeated. I would like to know if there is another way to write those ifs so there´s no line repeated. I´ve been thinking about it but I can't think of any alternative.

Thanks in advance.

def swap_elements(array, pos1, pos2):
    array[pos1], array[pos2] = array[pos2], array[pos1]
    return array

def insertion_sort(array, method):
    i = 1
    while i < len(array):
        key = array[i]
        j = 0
        while j < i:
            if method:
                if array[j] > key:
                    key = array[j]
                    array = swap_elements(array, i, j)
            else:
                if array[j] < key:
                    key = array[j]
                    array = swap_elements(array, i, j)
            j += 1
        i += 1

    return array

Latest version of the code:

def swap_elements(array, pos1, pos2):
    array[pos1], array[pos2] = array[pos2], array[pos1]

def insertion_sort(array, method):
    i = 1
    while i < len(array):
        key = array[i]
        j = 0
        while j < i:
            if (method and array[j] > key) or (not method and array[j] < key):
                key = array[j]
                swap_elements(array, i, j)
            j += 1
        i += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM