02.排序算法

排序算法

求最小值函数
1 #排序算法,求最小值函数
2 def findSmallest(arr):
3     samllest = arr[0]             #存储最小值
4     samllest_index = 0            #存储最小元素的索引
5     for i in range(1,len(arr)):
6         if arr[i] < samllest:
7             samllest = arr[i]
8             samllest_index = i
9     return samllest_index
 
 
 
使用排序算法编写排序函数
1 #排序算法
2 def selectionSort(arr):          #对数组进行排序
3     newarr = []
4     for i in range(len(arr)):
5         samllest = findSmallest(arr)    #调用 findSmallest()函数,找出数组中的最小值,并添加到新的数组中
6         newarr.append(arr.pop(samllest))
7     return newarr
8 
9 print(selectionSort([5,3,6,2,10])) #要排序的数组
 
 
 
 
 
排序结果:
1 [2, 3, 5, 6, 10]

猜你喜欢

转载自www.cnblogs.com/kadycui/p/9240207.html