-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.py
70 lines (54 loc) · 1.53 KB
/
sort.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
from memory_profiler import profile
import random
import time
numbers = list(range(1, 10**4))
k = len(numbers)
random.shuffle(numbers)
def timer(func):
def wrapper(*args, **kwargs):
before = time.monotonic()
retval = func(*args, **kwargs)
after = time.monotonic() - before
print(f"Function {func.__name__}: {after} seconds")
return retval
return wrapper
@profile
@timer
def insert_sort(nums: list) -> list:
nums = nums.copy()
for i in range(k-1):
m = i
for j in range(i+1, k):
if numbers[j] < numbers[m]:
m = j
numbers[i], numbers[m] = numbers[m], numbers[i]
return nums
@timer
def choice_sort(nums: list) -> list:
nums = nums.copy()
for i in range(k-1):
for j in range(i+1, k):
if nums[j] < nums[i]:
nums[j], nums[i] = nums[i], nums[j]
return nums
@timer
def bubble_sort(nums: list) -> list:
nums = nums.copy()
for i in range(1, k):
for j in range(0, k-i):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
return nums
def quick_sort(nums: list) -> list:
if len(nums) <= 1:
return nums
else:
q = random.choice(nums)
list1 = [elem for elem in nums if elem < q]
list2 = [q] * nums.count(q)
list3 = [elem for elem in nums if elem > q]
return quick_sort(list1) + list2 + quick_sort(list3)
choice_sort(numbers)
insert_sort(numbers)
bubble_sort(numbers)
quick_sort(numbers)