Skip to content

Commit 949f377

Browse files
committed
#17 stooge_sort
1 parent d0751ed commit 949f377

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

src/book/chapter7/problem4.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from book.data_structures import Array
2+
from book.data_structures import CT
3+
4+
5+
def stooge_sort(A: Array[CT], p: int, r: int) -> None:
6+
"""Sorts an array using stooge sort.
7+
8+
Implements:
9+
Stooge-Sort
10+
11+
Args:
12+
A: an Array containing the values to be sorted
13+
p: the lower index of the subarray to sort
14+
r: the upper index of the subarray to sort
15+
"""
16+
if A[p] > A[r]:
17+
A[p], A[r] = A[r], A[p]
18+
if p + 1 < r:
19+
k = (r - p + 1) // 3
20+
stooge_sort(A, p, r - k)
21+
stooge_sort(A, p + k, r)
22+
stooge_sort(A, p, r - k)

test/test_book/test_chapter7.py

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

6+
from book.chapter7.problem4 import stooge_sort
67
from book.chapter7.section1 import quicksort
78
from book.chapter7.section3 import randomized_quicksort
89
from book.chapter7.section4 import insertion_quicksort
@@ -61,3 +62,14 @@ def test_median_of_3_partition(self, data):
6162
for i in range_of(actual_pivot_index + 1, to=n):
6263
self.assertGreaterEqual(A[i], A[actual_pivot_index])
6364
self.assertArrayPermuted(A, elements, end=n)
65+
66+
@given(st.data())
67+
def test_stooge_sort(self, data):
68+
elements = data.draw(lists(integers(), min_size=1))
69+
A = create_array(elements)
70+
n = len(elements)
71+
72+
stooge_sort(A, 1, n)
73+
74+
self.assertArraySorted(A, end=n)
75+
self.assertArrayPermuted(A, elements, end=n)

0 commit comments

Comments
 (0)