Skip to content

Commit b3895d9

Browse files
committed
#17 insertion_quicksort
1 parent d9566fe commit b3895d9

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

src/book/chapter7/section4.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from book.chapter7.section1 import partition
2+
from book.data_structures import Array
3+
from book.data_structures import CT
4+
from util import range_of
5+
6+
7+
def insertion_quicksort(A: Array[CT], p: int, r: int, k: int) -> None:
8+
"""Sorts an array using quicksort, if the array size exceeds a given threshold, and using insertion sort otherwise.
9+
10+
Args:
11+
A: an Array containing the values to be sorted
12+
p: the lower index of the subarray to sort
13+
r: the upper index of the subarray to sort
14+
k: the threshold of the subarray size below which the subarray is to be sorted using insertion sort
15+
"""
16+
if p < r:
17+
if r - p + 1 >= k:
18+
q = partition(A, p, r)
19+
insertion_quicksort(A, p, q - 1, k)
20+
insertion_quicksort(A, q + 1, r, k)
21+
else:
22+
for i in range_of(p + 1, to=r):
23+
key = A[i]
24+
j = i - 1
25+
while j > 0 and A[j] > key:
26+
A[j + 1] = A[j]
27+
j -= 1
28+
A[j + 1] = key

test/test_book/test_chapter7.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
from book.chapter7.section1 import quicksort
77
from book.chapter7.section3 import randomized_quicksort
8+
from book.chapter7.section4 import insertion_quicksort
89
from test_case import ClrsTestCase
910
from test_util import create_array
1011

@@ -32,3 +33,15 @@ def test_randomized_quicksort(self, data):
3233

3334
self.assertArraySorted(A, end=n)
3435
self.assertArrayPermuted(A, elements, end=n)
36+
37+
@given(st.data())
38+
def test_insertion_quicksort(self, data):
39+
elements = data.draw(lists(integers(), min_size=1))
40+
A = create_array(elements)
41+
n = len(elements)
42+
k = data.draw(integers(min_value=1, max_value=n))
43+
44+
insertion_quicksort(A, 1, n, k)
45+
46+
self.assertArraySorted(A, end=n)
47+
self.assertArrayPermuted(A, elements, end=n)

0 commit comments

Comments
 (0)