插入类排序法
简单插入排序法(选择排序法)
# Finds the smallest value in an array
def findSmallest(arr):#用于找出最小值的函数
# Stores the smallest value
smallest = arr[0]
# Stores the index of the smallest value
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
#这里为何返回的是最小值的索引?
# Sort array
def selectionSort(arr):
newArr = []
for i in range(len(arr)):
# Finds the smallest element in the array and adds it to the new array
smallest = findSmallest(arr)
#找出数组中最小的元素,并将其加入到新数组中去;
newArr.append(arr.pop(smallest))
#每次用了pop之后,会删掉之前找到的最小值?
return newArr
print (selectionSort([5, 3, 6, 2, 10]))
输出:
[2, 3, 5, 6, 10]希尔排序法
Last updated
Was this helpful?