核心思想:给定一个列表或者数组等类似的数据结构,其下标L=0 to N-1
1.Find the position X of the smallest item in the range of [L…N−1],
发现下标范围【L N-1】中最小的位置X
2.Swap X-th item with the L-th item,
交换X位置与L位置的值
3.Increase the lower-bound L by 1 and repeat Step 1 until L = N-2.
增加下限L+1至L=N-2
方法1:
def find_smallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(len(arr)):
if smallest >= arr[i]:
smallest = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
new_arr = []
for i in range(len(arr)):
smallest = find_smallest(arr)
new_arr.append(arr.pop(smallest))
return new_arr
a = [1, 4, 3, 7]
print(selection_sort(a))
方法2:
def selection_sort2(list2):
for i in range(0, len(list2)-1):
min_ = i
for j in range(i + 1, len(list2)):
if list2[j] < list2[min_]:
min_ = j
list2[i], list2[min_] = list2[min_], list2[i] # swap
return list2
a = [1, 4, 3, 7]
print(selection_sort2(a))