1. 程式人生 > >09_資料結構與演算法_選擇排序_Python實現

09_資料結構與演算法_選擇排序_Python實現

"""
選擇排序:
    思路:
        遍歷整個列表,找到最小項的位置。
            如果該位置不是列表的第一個位置,演算法就會交換這兩個位置的項;
            然後演算法回到第二個位置並重復這個過程
"""

import random

#定義一個交換函式
def swap(lyst,i,j):
    temp = lyst[i]
    lyst[i] = lyst[j]
    lyst[j] = temp

#定義選擇排序
def selection_sort(lyst):
    i = 0
    while i < len(lyst) - 1:
        min_index = i
        j = i + 1
        while j < len(lyst):                    #遍歷當前子列表尋找最小項index
            if lyst[j] < lyst[min_index]:
                min_index = j
            j += 1
        if min_index != i:
            swap(lyst,min_index,i)
        i += 1
    return lyst

def test_sort():
    lyst = list(range(10))
    lyst = random.shuffle(lyst)
    assert selection_sort(lyst) == lyst

if __name__ == "__main__":
    test_sort()