time complexity:
Optimal Time Complexity: O(n^2) Worst Time Complexity: O(n^2) Stability: Unstable
Ideas:
1. Compare the first element of the unsorted array with all the following elements one by one. If it is greater than one of the following elements, exchange the position with it
2. In this way, the first element at the top of the round is the smallest one, and then continue to step 1 of the bracelet to find the second smallest element
Code
def select_sort(array):
"""
选择排序
"""
n = len(array)
for i in range(n): # 取第一个数的下标
for j in range(i+1, n): # 取后面每一个数的下标
if array[i] > array[j]: # 前一个数与后一个数比较
array[i], array[j] = array[j], array[i]
return array
array = [5, 2, 7, 3, 1, 8, 6, 4, 9]
res = select_sort(array) # 选择排序
print(res)
output result
[1, 2, 3, 4, 5, 6, 7, 8, 9]