1
1
import random
2
+ from collections import Counter
2
3
3
4
random .seed (42 )
4
5
@@ -15,11 +16,9 @@ def quicksort(arr, start, end):
15
16
"""
16
17
just by last element
17
18
"""
18
- original = arr [:] # for shallow copy
19
+ # original = arr[:] # for shallow copy
20
+ invariant = Counter (arr )
19
21
if start >= end :
20
- # assert on sorting invariant:
21
- # all elements have to match before and after, only position changes
22
- assert set (original ) == set (arr ), "dang we lost someone"
23
22
return arr
24
23
pivot = arr [end ]
25
24
n = end
@@ -34,7 +33,7 @@ def quicksort(arr, start, end):
34
33
print (f"{ start = } , { end = } " )
35
34
print (arr )
36
35
print ("pivot is:" , pivot )
37
-
36
+
38
37
for j in range (start , end ):
39
38
if arr [j ] < pivot :
40
39
i += 1
@@ -46,6 +45,11 @@ def quicksort(arr, start, end):
46
45
arr [end ] = arr [i + 1 ]
47
46
arr [i + 1 ] = pivot
48
47
48
+ # assert on sorting invariant:
49
+ # all elements have to match before and after, only position changes
50
+ modified = Counter (arr )
51
+ assert all ([invariant [key ] == modified [key ] for key in invariant .keys ()]), "dang we lost someone"
52
+
49
53
quicksort (arr , start , i )
50
54
quicksort (arr , i + 2 , end )
51
55
return arr
@@ -56,8 +60,8 @@ def quicksort(arr, start, end):
56
60
print (f"Total number of operations: { n_operations } " )
57
61
58
62
# testing suite
59
- recursion_depth = 0
60
63
n_operations = 0
61
64
for i in range (100 ):
65
+ recursion_depth = 0
62
66
quicksort (random_array (100 , 0 , 100 ), 0 , 99 )
63
67
print (f"Average number of operations: { n_operations / 100 } " )
0 commit comments