-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselection_sorting.py
More file actions
55 lines (46 loc) · 1.45 KB
/
selection_sorting.py
File metadata and controls
55 lines (46 loc) · 1.45 KB
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
#!python3
from numpy import random
from time import perf_counter
def selection_sort(array):
"a is a list like iterable. returns sorted version of a"
for i in range(len(array)):
j = 1
k=i
while i+j<len(array):
if array[i+j] < array[k]:
k = i+j
j+=1
array[i], array[k] = array[k], array[i]
return array
def selection_sort_withEAFP(array):
"a is a list like iterable. returns sorted version of a"
"also implements EAFP principle as opposed to naive method above"
for i in range(len(array)):
j = 1
k=i
#while i+j<len(array):
controller = True
while controller:
try:
if array[i+j] < array[k]:
k = i+j
j+=1
except IndexError:
controller = False
array[i], array[k] = array[k], array[i]
return array
def main():
a = random.randint(1000, size=5_000)
print(a)
start = perf_counter()
print(selection_sort(a))
print(f"naive selection: it took {(perf_counter() - start):.2f} "\
f"seconds to sort {len(a):,} items\n")
a = random.randint(1000, size=5_000)
print(a)
start = perf_counter()
print(selection_sort_withEAFP(a))
print(f"selection with EAFP: it took {(perf_counter() - start):.2f} "\
f"seconds to sort {len(a):,} items")
if __name__ == "__main__":
main()