时间复杂度:
最好情况:; 平均情况: 最坏: 不稳定
import random
import time
def selectionSort(arr):
for i in range(0,len(arr)-1):
# 假定arr[i]是第i-th小的
minIndex=i
# 查询真正的第i-th小的,下标赋值给minIndex
for j in range(i+1,len(arr)):
if arr[j]<arr[minIndex]:
minIndex=j
# 把第i-th小的放到i中
swap(arr,minIndex,i)
return arr
def swap(arr,i,j):
temp=arr[i]
arr[i]=arr[j]
arr[j]=temp
# 测试准确
def test1():
arr=[random.randint(0,99) for _ in range(0,10)]
print(arr)
selectionSort(arr)
print(arr)
# 测试时间
def test2():
arr=[random.randint(0,50000) for _ in range(0,50000)]
start=time.time()
print("start:",start," seconds")
selectionSort(arr)
end =time.time()
print("end:",end," seconds")
print("cost time:",end-start," seconds")
if __name__=="__main__":
test1()
# cost time: 57.227521657943726 seconds
# test2()
[8, 43, 12, 31, 34, 34, 92, 62, 2, 58]
[2, 8, 12, 31, 34, 34, 43, 58, 62, 92]
start: 1715912957.537102 seconds
end: 1715913008.9962237 seconds
cost time: 51.45912170410156 seconds