-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray.py
103 lines (85 loc) · 1.94 KB
/
array.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
arrays = [
[6, 2, 3, 1, 9, 0, 5],
[1, 2, 3, 5, 4, 5, 6, 7, 8, 7, 8, 9, 10]
]
def insertion_sort(xs):
"""
Stable
Space O(1)
Time O(n^2)
Adaptive O(n) when nearly sorted
"""
for i in range(len(xs)):
for j in range(i, 0, -1):
if xs[j] > xs[j - 1]:
break
xs[j], xs[j - 1] = xs[j - 1], xs[j]
return xs
def selection_sort(xs):
"""
Not stable
Space O(1)
Time O(n^2)
Low number of swaps O(n)
Not adaptive
"""
n = len(xs)
for i in range(n):
k = i
for j in range(i + 1, n):
if xs[j] < xs[k]:
k = j
xs[i], xs[k] = xs[k], xs[i]
return xs
def bubble_sort(xs):
"""
Stable
Space O(1)
Time O(n^2)
Adaptive O(n) when nearly sorted
"""
n = len(xs)
for i in range(n):
ordered = True
for j in range(n - 1, i, -1):
if xs[j] < xs[j-1]:
ordered = False
xs[j-1], xs[j] = xs[j], xs[j-1]
if ordered:
break
return xs
def merge_sort(xs):
"""
Stable
Space O(n)
Time O(nlogn)
Not adaptive
Good for linked list
"""
n = len(xs)
if n <= 1:
return xs
mid = n//2
left = merge_sort(xs[:mid])
right = merge_sort(xs[mid:])
result = []
while left and right:
if left[0] < right[0]:
result.append(left[0])
left = left[1:]
else:
result.append(right[0])
right = right[1:]
result += left
result += right
return result
sorting_methods = [insertion_sort, selection_sort, bubble_sort, merge_sort]
for method in sorting_methods:
for array in arrays:
result = method(array[:])
if result == sorted(array):
print(method.__name__, 'Works')
else:
print(method.__name__, 'Does not work')
print(array)
print(result)