Skip to content

Commit e1bf475

Browse files
committed
#17 tre_quicksort
1 parent 949f377 commit e1bf475

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

src/book/chapter7/problem5.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from book.chapter7.section1 import partition
2+
from book.data_structures import Array
3+
from book.data_structures import CT
4+
5+
6+
def tre_quicksort(A: Array[CT], p: int, r: int) -> None:
7+
"""Sorts an array using quicksort with tail-recursion elimination.
8+
9+
Implements:
10+
TRE-Quicksort
11+
12+
Args:
13+
A: an Array containing the values to be sorted
14+
p: the lower index of the subarray to sort
15+
r: the upper index of the subarray to sort
16+
"""
17+
while p < r:
18+
q = partition(A, p, r)
19+
tre_quicksort(A, p, q - 1)
20+
p = q + 1

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.problem4 import stooge_sort
7+
from book.chapter7.problem5 import tre_quicksort
78
from book.chapter7.section1 import quicksort
89
from book.chapter7.section3 import randomized_quicksort
910
from book.chapter7.section4 import insertion_quicksort
@@ -73,3 +74,14 @@ def test_stooge_sort(self, data):
7374

7475
self.assertArraySorted(A, end=n)
7576
self.assertArrayPermuted(A, elements, end=n)
77+
78+
@given(st.data())
79+
def test_tre_quicksort(self, data):
80+
elements = data.draw(lists(integers(), min_size=1))
81+
A = create_array(elements)
82+
n = len(elements)
83+
84+
tre_quicksort(A, 1, n)
85+
86+
self.assertArraySorted(A, end=n)
87+
self.assertArrayPermuted(A, elements, end=n)

0 commit comments

Comments
 (0)