|
| 1 | +from book.data_structures import Array |
| 2 | +from book.data_structures import CT |
| 3 | +from util import range_of |
| 4 | + |
| 5 | + |
| 6 | +def partition_decreasing(A: Array[CT], p: int, r: int) -> int: |
| 7 | + """Partitions an array into two subarrays, the low side and the high side, such that each element in the low side of |
| 8 | + the partition is greater than or equal to the pivot value, which is, in turn, greater than or equal to each element |
| 9 | + in the high side. |
| 10 | +
|
| 11 | + Args: |
| 12 | + A: an Array to partition |
| 13 | + p: the lower index of the subarray to partition |
| 14 | + r: the upper index of the subarray to partition |
| 15 | +
|
| 16 | + Returns: |
| 17 | + The index q, such that each element in A[p:q - 1] is greater than or equal to A[q], and that A[q] is greater |
| 18 | + than or equal to each element in A[q + 1:r]. |
| 19 | + """ |
| 20 | + x = A[r] |
| 21 | + i = p - 1 |
| 22 | + for j in range_of(p, to=r - 1): |
| 23 | + if A[j] >= x: |
| 24 | + i += 1 |
| 25 | + A[i], A[j] = A[j], A[i] |
| 26 | + A[i + 1], A[r] = A[r], A[i + 1] |
| 27 | + return i + 1 |
| 28 | + |
| 29 | + |
| 30 | +def quicksort_decreasing(A: Array[CT], p: int, r: int) -> None: |
| 31 | + """Sorts an array into monotonically decreasing order using quicksort. |
| 32 | +
|
| 33 | + Args: |
| 34 | + A: an Array containing the values to be sorted |
| 35 | + p: the lower index of the subarray to sort |
| 36 | + r: the upper index of the subarray to sort |
| 37 | + """ |
| 38 | + if p < r: |
| 39 | + q = partition_decreasing(A, p, r) |
| 40 | + quicksort_decreasing(A, p, q - 1) |
| 41 | + quicksort_decreasing(A, q + 1, r) |
0 commit comments