排序算法-冒泡排序、选择排序

冒泡排序

alist = [3, 5, 2, 4, 1, 9]


def bubbleSort(alist):
    for i in range(0, len(alist) - 1):
        for j in range(0, len(alist) - i - 1):
            if alist[j] > alist[j + 1]:
                alist[j], alist[j + 1] = alist[j + 1], alist[j]
    return alist

ret=bubbleSort(alist)
print(ret)

选择排序

alist = [3, 5, 2, 4, 1, 9]


def choiceSort(alist):
    for i in range(0, len(alist) - 1):
        max_index = 0
        for j in range(1, len(alist) - i):
            if alist[j] > alist[max_index]:
                max_index = j
            alist[len(alist) - 1 - i], alist[max_index] = alist[max_index], alist[len(alist) - 1 - i]
    return alist

ret = choiceSort(alist)
print(ret)

 

上一篇:冒泡排序及其优化


下一篇:18. java之list集合