Python implementation choices to sort and bubble sort

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_43849107/article/details/102770564

Selection Sort

def SelectSort(arr):
    for i in range(len(arr) - 1):
        min_index = i
        for j in range(i + 1, len(arr)):
            if arr[j] < arr[min_index]:
                min_index = j
        arr[min_index], arr[j] = arr[j], arr[min_index]
    return arr


if __name__ == '__main__':
    print("请输入数组,整数与整数之间用空格隔开")
    arr = [int(n) for n in input().split()]
    SelectSort(arr)
    print("从小到大排序:", end="")
    print(arr)

Bubble Sort

def BubbleSort(arr):
    exchange = len(arr) - 1
    while (exchange != 0):
        bound = exchange
        exchange = 0
        for j in range(bound):
            if (arr[j] > arr[j + 1]):
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                exchange = j
    return arr


if __name__ == '__main__':
    print("请输入数组,整数与整数之间用空格隔开")
    arr = [int(n) for n in input().split()]
    BubbleSort(arr)
    print("从小到大排序:", end="")
    print(arr)

Guess you like

Origin blog.csdn.net/weixin_43849107/article/details/102770564