Skip to content

Commit 87fb6c4

Browse files
committed
#83 quicksort_decreasing
1 parent 6fd4c61 commit 87fb6c4

2 files changed

Lines changed: 54 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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)

test/test_solutions/test_chapter7.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import math
2+
import operator
23

34
from hypothesis import given
45
from hypothesis import strategies as st
@@ -7,6 +8,7 @@
78
from hypothesis.strategies import lists
89

910
from solutions.chapter7.section1.exercise2 import fair_partition
11+
from solutions.chapter7.section1.exercise4 import quicksort_decreasing
1012
from test_case import ClrsTestCase
1113
from test_util import create_array
1214
from util import range_of
@@ -41,3 +43,14 @@ def test_fair_partition_all_values_equal(self, data):
4143
actual_split_index = fair_partition(A, 1, n)
4244

4345
self.assertEqual(actual_split_index, (n + 1) // 2)
46+
47+
@given(st.data())
48+
def test_quicksort_decreasing(self, data):
49+
elements = data.draw(lists(integers(), min_size=1))
50+
A = create_array(elements)
51+
n = len(elements)
52+
53+
quicksort_decreasing(A, 1, n)
54+
55+
self.assertArraySorted(A, end=n, cmp=operator.ge)
56+
self.assertArrayPermuted(A, elements, end=n)

0 commit comments

Comments
 (0)