11from book .chapter7 .section1 import partition
22from book .data_structures import Array
33from book .data_structures import CT
4+ from solutions .chapter5 .section1 .exercise2 import random
45from util import range_of
56
67
@@ -26,3 +27,28 @@ def insertion_quicksort(A: Array[CT], p: int, r: int, k: int) -> None:
2627 A [j + 1 ] = A [j ]
2728 j -= 1
2829 A [j + 1 ] = key
30+
31+
32+ def median_of_3_partition (A : Array [CT ], p : int , r : int ) -> int :
33+ """Partitions an array into two subarrays, the low side and the high side, such that each element in the low side of
34+ the partition is less than or equal to the pivot value, which is, in turn, less than or equal to each element in the
35+ high side. Uses a median of randomly picked three elements as the pivot.
36+
37+ Args:
38+ A: an Array to partition
39+ p: the lower index of the subarray to partition
40+ r: the upper index of the subarray to partition
41+
42+ Returns:
43+ The index q, such that each element in A[p:q - 1] is less than or equal to A[q], and that A[q] is less than or
44+ equal to each element in A[q + 1:r].
45+ """
46+ i1 , i2 , i3 = random (p , r ), random (p , r ), random (p , r )
47+ if A [i2 ] <= A [i1 ] <= A [i3 ] or A [i3 ] <= A [i1 ] <= A [i2 ]:
48+ m = i1
49+ elif A [i1 ] <= A [i2 ] <= A [i3 ] or A [i3 ] <= A [i2 ] <= A [i1 ]:
50+ m = i2
51+ else :
52+ m = i3
53+ A [m ], A [r ] = A [r ], A [m ]
54+ return partition (A , p , r )
0 commit comments