import time def insertionsort for in range len для того чтобы цикл не

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import time
def insertionsort(L):
for i in range(1, len(L)):
x = i
# x>0 для того, чтобы цикл не выходил за пределы массива
while x > 0 and L[x-1] > L[x]:
L[x-1], L[x] = L[x], L[x-1]
x-=1
return L
##################################
#https://www.toptal.com/developers/sorting-algorithms/merge-sort
def mergesort(L):
if len(L)>1:
centr = len(L)//2
levaya = L[:centr]
pravaya = L[centr:]
mergesort(levaya)
mergesort(pravaya)
i=0
j=0
k=0
while i < len(levaya) and j < len(pravaya):
if levaya[i] < pravaya[j]:
L[k]=levaya[i]
i=i+1
else:
L[k]=pravaya[j]
j=j+1
k=k+1
while i < len(levaya):
L[k]=levaya[i]
i=i+1
k=k+1
while j < len(pravaya):
L[k]=pravaya[j]
j=j+1
k=k+1
return L
###### pokaz vremeni ######
def print_times(L):
print("{0:7}".format(len(L)), end=":")
for func in (insertionsort, mergesort):
L_copy = L[:]
t1 = time.perf_counter()
func(L_copy)
t2 = time.perf_counter()
print("{0:10.1f}".format((t2-t1)*1000.), end='')
print()
########### testirovanie ###########
import random
a = [10,1000,2000,3000,4000,5000,10000]
for t in a:
L = [random.randint(1,x*13) for x in range (1,t+1)]
print_times(L)