1616- We should be able to easily change which partitioning strategy we use in the implementation.
1717- Skiena points out that some inputs (which?) can be pathological, but that pre-shuffling our input takes care of most of these
1818"""
19+ import random
1920
2021
22+ def lomuto_partition (arr , low , high ):
23+ """
24+ The Lomuto partition boils down to "pick a partition element,
25+ move everything smaller to the right of it, then swap it in at the end":
26+ """
27+ pivot = arr [high ]
28+ i = low
29+ for j in range (low , high ):
30+ if arr [j ] < pivot :
31+ arr [j ], arr [i ] = arr [i ], arr [j ]
32+ i += 1
33+ arr [i ], arr [high ] = arr [high ], arr [i ]
34+ return i
2135
22- def lomuto_partition ():
23- pass
2436
25- def hoare_partition ():
26- pass
27-
28- def sort (arr , partition_fn ):
29- return arr
30-
31- def quicksort (arr , partition_fn , shuffle = True ):
37+ def quicksort (arr , partition_fn , shuffle = False ):
3238 if shuffle :
3339 # do shuffling here
34- pass
35- return sort (arr , partition_fn )
36-
37- if __name__ == '__main__' :
38- test_arrs = [
39- [],
40- [1 ]
41- [6 , 5 , 4 , 3 , 2 , 1 ],
42- [1 , 2 , 3 , 4 , 5 , 6 ]
43- [1 , 1 , 1 , 1 , 1 , 1 ],
44- [5 , 1 , 3 , 4 , 5 , 10 ],
40+ random .shuffle (arr )
41+
42+ def sort (arr , low , high ):
43+ if low < high :
44+ pivot = partition_fn (arr , low , high )
45+ sort (arr , low , pivot - 1 )
46+ sort (arr , pivot + 1 , high )
47+
48+ sort (arr , 0 , len (arr ) - 1 )
49+
50+
51+ if __name__ == "__main__" :
52+ test_pairs = [
53+ ([], []),
54+ ([1 ], [1 ]),
55+ # Pathological case 1
56+ ([10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 ], [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ],),
57+ ([1 , 2 , 3 , 4 , 5 , 6 ], [1 , 2 , 3 , 4 , 5 , 6 ]),
58+ ([1 , 1 , 1 , 1 , 1 , 1 ], [1 , 1 , 1 , 1 , 1 , 1 ]),
59+ ([5 , 1 , 3 , 4 , 5 , 10 ], [1 , 3 , 4 , 5 , 5 , 10 ]),
4560 ]
46- for arr in test_arrs :
47- assert quicksort (arr , lomuto_partition ) == sorted (arr )
48- assert quicksort (arr , hoare_partition ) == sorted (arr )
61+ for pair in test_pairs :
62+ actual , expected = pair
63+ quicksort (actual , lomuto_partition )
64+ assert actual == expected
0 commit comments