Skip to content

Commit 71133a2

Browse files
committed
#17 hoare_partition
1 parent e1bf475 commit 71133a2

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/book/chapter7/problem1.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from book.data_structures import Array
2+
from book.data_structures import CT
3+
4+
5+
def hoare_partition(A: Array[CT], p: int, r: int) -> int:
6+
"""Partitions an array into two subarrays, the low side and the high side, such that each element in the low side of
7+
the partition is less than or equal to each element in the high side. Uses the original algorithm invented by
8+
C. A. R. Hoare.
9+
10+
Implements:
11+
Hoare-Partition
12+
13+
Args:
14+
A: an Array to partition
15+
p: the lower index of the subarray to partition
16+
r: the upper index of the subarray to partition
17+
18+
Returns:
19+
The index j such that each element in A[p:j] is less than or equal to each element in A[j + 1:r].
20+
"""
21+
x = A[p]
22+
i = p - 1
23+
j = r + 1
24+
while True:
25+
while True:
26+
j -= 1
27+
if A[j] <= x:
28+
break
29+
while True:
30+
i += 1
31+
if A[i] >= x:
32+
break
33+
if i < j:
34+
A[i], A[j] = A[j], A[i]
35+
else:
36+
return j

test/test_book/test_chapter7.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
1+
import math
2+
13
from hypothesis import given
24
from hypothesis import strategies as st
35
from hypothesis.strategies import integers
46
from hypothesis.strategies import lists
57

8+
from book.chapter7.problem1 import hoare_partition
69
from book.chapter7.problem4 import stooge_sort
710
from book.chapter7.problem5 import tre_quicksort
811
from book.chapter7.section1 import quicksort
@@ -64,6 +67,23 @@ def test_median_of_3_partition(self, data):
6467
self.assertGreaterEqual(A[i], A[actual_pivot_index])
6568
self.assertArrayPermuted(A, elements, end=n)
6669

70+
@given(st.data())
71+
def test_hoare_partition(self, data):
72+
elements = data.draw(lists(integers(), min_size=1))
73+
A = create_array(elements)
74+
n = len(elements)
75+
76+
actual_split_index = hoare_partition(A, 1, n)
77+
78+
left_max = -math.inf
79+
right_min = math.inf
80+
for i in range_of(1, to=actual_split_index):
81+
left_max = max(left_max, A[i])
82+
for i in range_of(actual_split_index + 1, to=n):
83+
right_min = min(right_min, A[i])
84+
self.assertLessEqual(left_max, right_min)
85+
self.assertArrayPermuted(A, elements, end=n)
86+
6787
@given(st.data())
6888
def test_stooge_sort(self, data):
6989
elements = data.draw(lists(integers(), min_size=1))

0 commit comments

Comments
 (0)