随着排序的进行,每次需要检查的元素在逐渐减少,最后一次需要检查的元素都只有一个。如下,先实现一个查找最小元素的方法,然后进行新数组的生成。
1、数值排序
def findSmallest(arr):
smalllest = arr[0]
smalllest_index = 0
for i in range(1,len(arr)):
if arr[i] < smalllest:
smalllest = arr[i]
smalllest_index = i
return smalllest_index
def selecttionSort(arr):
newArr = []
for i in range(len(arr)):
smallest = findSmallest(arr)
print(arr)
newArr.append(arr.pop(smallest))
return newArr
print(selecttionSort([5,3,6,2,10]))
2、乐队排序
def paixu(yuedui):
smallest_value = yuedui[0]
smallest_key = 0
for i in range(len(yuedui)):
if yuedui[i][1] < smallest_value[1]:
smallest_key = i
return smallest_key
def solution(arr):
newArry = []
for i in range(0, len(arr)):
newArry.append(arr.pop(paixu(arr)))
return newArry
yuedui = [
("夜曲", 30),
("晴天", 20),
("断了的弦", 33),
("漂移", 35),
("青花瓷", 36),
]
print(solution(yuedui))