编辑:我需要一个计时器,用于计算用户输入无序列表后需要花费多长时间。
我似乎无法运行time_selection_sort函数。我希望计时器在用户输入列表后立即开始。
from time import perf_counter
def swap(lst, i, j):
tmp = lst[i]
lst[i] = lst[j]
lst[j] = tmp
def swap_if_greater(lst, i, j):
if lst[i] > lst[j]:
tmp = lst[i]
lst[i] = lst[j]
lst[j] = tmp
def find_index_of_min(lst):
min_index = 0
min_value = lst[0]
for i, value in enumerate(lst):
if value < min_value:
min_index = i
min_value = value
return min_index
def selection_sort_out_of_place(input_list):
# make a copy so we don't destroy the original data
input_list = list(input_list)
output_list = []
# sort values into output_list, one at a time
while input_list:
print('Input list:', repr(input_list))
print('Output list:', repr(output_list))
min_index = find_index_of_min(input_list)
value = input_list.pop(min_index)
print('Sorting the value', repr(value))
output_list.append(value)
return output_list
def time_selection_sort(input_list):
# generate random list
lst = selection_sort_out_of_place(input_list)
# measure running time
start_time = perf_counter()
insertion_sort(lst)
end_time = perf_counter()
# return time in milliseconds
return 1000 * (end_time - start_time)
t = time_selection_sort(100)
print('Time:', t, 'ms')