- ## 选择排序需要执行 n 次时间为 O 的操作, 所以总时间为 O
- def find_smallest(arr):
- """return the index of the smallest element"""
- smallest = arr[0]
- smallest_index = 0
- for i in range(0, len(arr)):
- if arr[i] < smallest:
- smallest = arr[i]
- smallest_index = i
- return smallest_index
- def selection_sort(arr):
- sorted_arr = []
- for i in range(0, len(arr)):
- smallest_index = find_smallest(arr)
- sorted_arr.append(arr.pop(smallest_index))
- return sorted_arr
- print(selection_sort([2,3,4,5,7,2,21,-2,-4,-9]))
- # [-9, -4, -2, 2, 2, 3, 4, 5, 7, 21]
选择排序
来源: http://www.bubuko.com/infodetail-2693708.html