|
| 1 | +from book.chapter7.section1 import partition |
| 2 | +from book.data_structures import Array |
| 3 | +from book.data_structures import CT |
| 4 | +from solutions.chapter5.section1.exercise2 import random |
| 5 | + |
| 6 | + |
| 7 | +def randomized_partition(A: Array[CT], p: int, r: int) -> int: |
| 8 | + """Partitions an array into two subarrays, the low side and the high side, such that each element in the low side of |
| 9 | + the partition is less than or equal to the pivot value, which is, in turn, less than or equal to each element in the |
| 10 | + high side. Chooses the pivot element randomly. |
| 11 | +
|
| 12 | + Implements: |
| 13 | + Randomized-Partition |
| 14 | +
|
| 15 | + Args: |
| 16 | + A: an Array to partition |
| 17 | + p: the lower index of the subarray to partition |
| 18 | + r: the upper index of the subarray to partition |
| 19 | +
|
| 20 | + Returns: |
| 21 | + 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 |
| 22 | + equal to each element in A[q + 1:r]. |
| 23 | + """ |
| 24 | + i = random(p, r) |
| 25 | + A[r], A[i] = A[i], A[r] |
| 26 | + return partition(A, p, r) |
| 27 | + |
| 28 | + |
| 29 | +def randomized_quicksort(A: Array[CT], p: int, r: int) -> None: |
| 30 | + """Sorts an array using the randomized version of quicksort. |
| 31 | +
|
| 32 | + Implements: |
| 33 | + Randomized-Quicksort |
| 34 | +
|
| 35 | + Args: |
| 36 | + A: an Array containing the values to be sorted |
| 37 | + p: the lower index of the subarray to sort |
| 38 | + r: the upper index of the subarray to sort |
| 39 | + """ |
| 40 | + if p < r: |
| 41 | + q = randomized_partition(A, p, r) |
| 42 | + randomized_quicksort(A, p, q - 1) |
| 43 | + randomized_quicksort(A, q + 1, r) |
0 commit comments