09 資料結構與演算法 選擇排序

2021-08-30 04:37:09 字數 818 閱讀 2870

"""

選擇排序:

思路:遍歷整個列表,找到最小項的位置。

如果該位置不是列表的第乙個位置,演算法就會交換這兩個位置的項;

然後演算法回到第二個位置並重複這個過程

"""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()

資料結構與演算法 排序 選擇排序

資料結構與演算法 排序 選擇排序 sort selectsort include includevoid selectsort int list,int len if print list,len for selectsort int minkey int list,int i,int len if...

資料結構與演算法 選擇排序

選擇排序 從小到大 的基本思想是,首先,選出最小的數,放在第乙個位置 然後,選出第二小的數,放在第二個位置 以此類推,直到所有的數從小到大排序。在實現上,我們通常是先確定第i小的數所在的位置,然後,將其與第i個數進行交換。下面,以對 3 2 4 1 進行選擇排序說明排序過程,使用min index ...

資料結構與演算法 選擇排序

1 什麼是程式?程式 資料結構 演算法 2 選擇排序 selection sort 基本思想 我們從第乙個位置開始,依次和後面的值進行比較,如找到比第乙個值小的,二者進行交換。交換後第乙個位置的值已經確定下來,我們再從第二個位置開始,依次和後面的進行比較,依次類推,知道所有的值都比較完成,到此選擇排...