1. 程式人生 > >Python實現指定排序函式進行排序

Python實現指定排序函式進行排序

程式說明:

利用氣泡排序、直接選擇排序分別實現指定陣列的升序、降序排列,並可以選擇指定排序函式。

Python程式碼如下:

#氣泡排序法實現升序排列
def bubble_sort(lists, sort = None):
    if not sort:
        count = len(lists)
        for i in range(0, count):
            for j in range(i + 1, count):
                if lists[i] > lists[j]:
                    lists[i], lists[j] = lists[j], lists[i]
        return lists
    else:
        return sort(lists)
#直接選擇排序法實現降序排列
def select_sort(lists):
    count = len(lists)
    for i in range(0, count):
        max = i
        for j in range(i + 1, count):
            if lists[max] < lists[j]:
                max = j
        lists[max], lists[i] = lists[i], lists[max]
    return lists

#輸入資料測試
s = [1, 5, 3, 9, 7, 13, 78, 54, 43, 32, 1, 4, 10]
print(s)
print('bubble_sort= %s' %bubble_sort(s))
print('select_sort= %s' %bubble_sort(s, sort = select_sort))
輸出結果如下:
[1, 5, 3, 9, 7, 13, 78, 54, 43, 32, 1, 4, 10]
bubble_list= [1, 1, 3, 4, 5, 7, 9, 10, 13, 32, 43, 54, 78]
select_list= [78, 54, 43, 32, 13, 10, 9, 7, 5, 4, 3, 1, 1]

參考資料: