Skip to content

Commit d9566fe

Browse files
committed
#17 randomized_partition, randomized_quicksort
1 parent 079e4f3 commit d9566fe

2 files changed

Lines changed: 55 additions & 0 deletions

File tree

src/book/chapter7/section3.py

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

test/test_book/test_chapter7.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from hypothesis.strategies import lists
55

66
from book.chapter7.section1 import quicksort
7+
from book.chapter7.section3 import randomized_quicksort
78
from test_case import ClrsTestCase
89
from test_util import create_array
910

@@ -20,3 +21,14 @@ def test_quicksort(self, data):
2021

2122
self.assertArraySorted(A, end=n)
2223
self.assertArrayPermuted(A, elements, end=n)
24+
25+
@given(st.data())
26+
def test_randomized_quicksort(self, data):
27+
elements = data.draw(lists(integers(), min_size=1))
28+
A = create_array(elements)
29+
n = len(elements)
30+
31+
randomized_quicksort(A, 1, n)
32+
33+
self.assertArraySorted(A, end=n)
34+
self.assertArrayPermuted(A, elements, end=n)

0 commit comments

Comments
 (0)