-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgos.py
445 lines (341 loc) · 10.7 KB
/
algos.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import random
import time
from enum import Enum
import numpy as np
import matplotlib . pyplot as plot
import sys
import threading
threading.stack_size(67108864) #64MB
sys.setrecursionlimit(2 ** 20)
############################# sorts #############################
#Insertion Sort
def iS(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Selection Sort
def sS(arr):
# Traverse through all array elements
for i in range(len(arr)):
# Find the minimum element in remaining
# unsorted array
min_idx = i
for j in range(i + 1, len(arr)):
if arr[min_idx] > arr[j]:
min_idx = j
# Swap the found minimum element with
# the first element
arr[i], arr[min_idx] = arr[min_idx], arr[i]
# Heap Sort (auxiliary function)
def heapify(arr, N, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is
# greater than root
if l < N and arr[largest] < arr[l]:
largest = l
# See if right child of root exists and is
# greater than root
if r < N and arr[largest] < arr[r]:
largest = r
# Change root, if needed
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i] # swap
# Heapify the root.
heapify(arr, N, largest)
# Heap Sort (main hS function)
def hS(arr):
N = len(arr)
# Build a maxheap.
for i in range(N // 2 - 1, -1, -1):
heapify(arr, N, i)
# One by one extract elements
for i in range(N - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
# Merge Sort
def mS(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
mS(L)
# Sorting the second half
mS(R)
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
############################# usage functions #############################
#just separation from other entitis
def programStart():
for i in range(4):
print("---program start---")
#enum for sorts
class aSort(Enum):
iS = 1
sS = 2
hS = 3
mS = 4
#filling tab
def tabFill(arr, l=10, v=1, rand = True):
append = arr.append
if rand == True: # filling with randoms
for i in range(0, l): #packing tab
append(random.randrange(1, v)) #from 1 to valuemax
else:
for i in range(0, l): #packing tab
append(v)
#function measuring time of actions in parameters
def mTime(arr, sort: aSort):
avg = 0
iterations = repetitions
for i in range(iterations):
if sort == aSort.iS:
start_time = time.time()
iS(arr.copy())
stop_time = time.time() - start_time
elif sort == aSort.sS:
start_time = time.time()
sS(arr.copy())
stop_time = time.time() - start_time
elif sort == aSort.hS:
start_time = time.time()
hS(arr.copy())
stop_time = time.time() - start_time
elif sort == aSort.mS:
start_time = time.time()
hS(arr.copy())
stop_time = time.time() - start_time
avg += stop_time
stop_time = avg/iterations
return stop_time
#dividing resuilts for smaller tabs
def divresults(res, viS, vsS, vhS, vmS):
for i in res:
viS.append(i[0])
vsS.append(i[1])
vhS.append(i[2])
vmS.append(i[3])
#clearing
def aClear(r, res, viS, vsS, vhS, vmS, vTime):
del res
del viS
del vsS
del vhS
del vmS
del vTime
del r
#making graphs
def plotting(viS,vsS,vhS,vmS,vTime, num, title):
plotnumber = 0 + num #for graphs arrangement
#linear
plot.figure()
plot.plot(vTime, viS, vTime, vsS, vTime, vhS, vTime, vmS)
plot.title(title)
plot.xlabel('number of sorts')
plot.ylabel('time[s]')
plot.legend([ "iS","sS","hS","mS",])
plot.grid(True)
#logarithm
plot.figure()
plot.plot(vTime, viS, vTime, vsS, vTime, vhS, vTime, vmS)
plot.yscale('log')
plot.title(str(title + ' log'))
plot.xlabel('number of sorts')
plot.ylabel('time[s]')
plot.legend([ "iS","sS","hS","mS",])
plot.grid(True)
#generating v-shaped
def vSFillTab(l, low_num_tabs):
for i in range(1,low_num_tabs,2):
l.append(i)
l.insert(0, i+1)
#updating v-shaped
def vSAddToTab(l, step):
step = int(step/2)
for i in range(step):
first_num = l[0]
l.append(first_num+1)
l.insert(0, first_num + 2)
############################# main #############################
def main():
programStart()
#array settings
r = []
#l = 5000 #length of array # overwritten by
v = 150 #max value in array
#loop of 1 sort settings
startValue = 1000 #750
endValue = 2000 #3000
step = 75 #2 #50
global repetitions
repetitions= 10 #to generate avg
#bufored times
results = []
viS = []
vsS = []
vhS = []
vmS = []
vTime = []
tabFill(r, startValue, v)
print("startValue: ", startValue, " endValue: ", endValue, " with step: ", step)
################### for random ###################
for i in range(startValue, endValue, step):
vTime.append(i) #making y dimmension for plot
iResults = [] #iteration results in form [iS, sS, hS, mS]
tabFill(r, step, v) #increasing list size by quant. of step random elements
print("Filling, len of arr: ", len(r), " of ", endValue)
for sort in (aSort):
#print(sort.value, "-", sort)
t = mTime(r, sort)
#print(sort.name," %s seconds " % (t))
iResults.append(t)
results.append(iResults.copy())
iResults.clear()
print("end of this iteration \n")
#print(results)
divresults(results, viS, vsS, vhS, vmS) #dividing results into results per sort
plotting(viS,vsS,vhS,vmS,vTime, 1, "randoms")
aClear(r, results, viS, vsS, vhS, vmS, vTime)
################### for sorted asc ###################
r = []
results = []
viS = []
vsS = []
vhS = []
vmS = []
vTime = []
tabFill(r, startValue, v)
print("startValue: ", startValue, " endValue: ", endValue, " with step: ", step)
for i in range(startValue, endValue, step):
vTime.append(i)
iResults = []
tabFill(r, step, v)
print("Filling, len of arr: ", len(r), " of ", endValue)
mS(r) #here's the difference
for sort in (aSort):
#print(sort.value, "-", sort)
t = mTime(r, sort)
#print(sort.name," %s seconds " % (t))
iResults.append(t)
results.append(iResults.copy())
iResults.clear()
print("end of this iteration \n")
divresults(results, viS, vsS, vhS, vmS)
plotting(viS,vsS,vhS,vmS,vTime, 5, "sorted asc")
aClear(r, results, viS, vsS, vhS, vmS, vTime)
################### for sorted desc ###################
r = []
results = []
viS = []
vsS = []
vhS = []
vmS = []
vTime = []
tabFill(r, startValue, v)
print("startValue: ", startValue, " endValue: ", endValue, " with step: ", step)
for i in range(startValue, endValue, step):
vTime.append(i)
iResults = []
tabFill(r, step, v)
print("Filling, len of arr: ", len(r), " of ", endValue)
r.sort(reverse=True) #and here's the difference
for sort in (aSort):
#print(sort.value, "-", sort)
t = mTime(r, sort)
#print(sort.name," %s seconds " % (t))
iResults.append(t)
results.append(iResults.copy())
iResults.clear()
print("end of this iteration \n")
divresults(results, viS, vsS, vhS, vmS)
plotting(viS,vsS,vhS,vmS,vTime, 9, "sorted desc")
aClear(r, results, viS, vsS, vhS, vmS, vTime)
################### for const ###################
r = []
results = []
viS = []
vsS = []
vhS = []
vmS = []
vTime = []
tabFill(r, startValue, v)
print("startValue: ", startValue, " endValue: ", endValue, " with step: ", step)
for i in range(startValue, endValue, step):
vTime.append(i)
iResults = []
tabFill(r, step, v, False)
print("Filling, len of arr: ", len(r), " of ", endValue)
r.sort(reverse=True) #and here's the difference
for sort in (aSort):
#print(sort.value, "-", sort)
t = mTime(r, sort)
#print(sort.name," %s seconds " % (t))
iResults.append(t)
results.append(iResults.copy())
iResults.clear()
print("end of this iteration \n")
divresults(results, viS, vsS, vhS, vmS)
plotting(viS,vsS,vhS,vmS,vTime, 13, "const")
aClear(r, results, viS, vsS, vhS, vmS, vTime)
################### for v-shaped ###################
r = []
results = []
viS = []
vsS = []
vhS = []
vmS = []
vTime = []
vSFillTab(r, startValue)
print("startValue: ", startValue, " endValue: ", endValue, " with step: ", step)
for i in range(startValue, endValue, step):
vTime.append(i)
iResults = []
for sort in (aSort):
#print(sort.value, "-", sort)
t = mTime(r, sort)
#print(sort.name," %s seconds " % (t))
iResults.append(t)
results.append(iResults.copy())
iResults.clear()
print("Filling, len of arr: ", len(r), " of ", endValue)
vSAddToTab(r, step)
divresults(results, viS, vsS, vhS, vmS)
plotting(viS,vsS,vhS,vmS,vTime, 17, "v-shaped")
aClear(r, results, viS, vsS, vhS, vmS, vTime)
################### all sorts passed ###################
plot.show()
return 0
if __name__ == "__main__":
thread = threading.Thread(target=main)
thread.start()
#main()