我目前正在尝试在 python 中实现插入排序和选择排序。我的两个实现都有效。然而,当我对排序进行计时时,选择排序的执行速度始终比插入排序快 1.5 倍,尽管我的插入排序实现的比较次数大约是我的选择排序实现的一半。我似乎找不到原因。
def select_sort(data):
for i in range(len(data)):
minimum, index = None, i
for j in range(i, len(data)):
if minimum is None:
minimum = data[j]
if data[j] < minimum:
minimum = data[j]
index = j
data[i], data[index] = data[index], data[i]
return data
def insert_sort(data):
for i in range(1, len(data)):
for j in range(i, 0, -1):
if data[j] >= data[j - 1]:
break
data[j], data[j - 1] = data[j - 1], data[j]
return data
def time_sort(S):
elapsed = []
start = time()
insert_sort(copy(S))
elapsed.append(time() - start)
start = time()
select_sort(copy(S))
elapsed.append(time() - start)
return elapsed