1+ import random
2+
3+ random .seed (42 )
4+
5+ def random_array (length , bottom , top ):
6+ return [random .randint (bottom , top ) for i in range (length )]
7+
18arr = [8 , 2 , 4 , 7 , 1 , 3 , 9 , 6 , 5 ]
29#arr = [64, 34, 25, 12, 22, 11, 90, 110]
310
411recursion_depth = 0
12+ n_operations = 0
513
614def quicksort (arr , start , end ):
715 """
816 just by last element
917 """
1018 original = arr [:] # for shallow copy
1119 if start >= end :
12- assert all ([el in original for el in arr ]), "dang we lost someone"
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"
1323 return arr
1424 pivot = arr [end ]
1525 n = end
1626 i = start - 1
1727 swap = 0
1828
29+ global n_operations
1930 global recursion_depth
2031 recursion_depth += 1
32+
2133 print (10 * "=" , f" Quicksort: { recursion_depth } " , 10 * "=" )
2234 print (f"{ start = } , { end = } " )
2335 print (arr )
@@ -30,6 +42,7 @@ def quicksort(arr, start, end):
3042 swap = arr [j ]
3143 arr [j ] = arr [i ]
3244 arr [i ] = swap
45+ n_operations += 1
3346 arr [end ] = arr [i + 1 ]
3447 arr [i + 1 ] = pivot
3548
@@ -40,5 +53,11 @@ def quicksort(arr, start, end):
4053arr = quicksort (arr , 0 , len (arr )- 1 )
4154
4255print (f"\n Final { arr } " )
56+ print (f"Total number of operations: { n_operations } " )
4357
44-
58+ # testing suite
59+ recursion_depth = 0
60+ n_operations = 0
61+ for i in range (100 ):
62+ quicksort (random_array (100 , 0 , 100 ), 0 , 99 )
63+ print (f"Average number of operations: { n_operations / 100 } " )
0 commit comments