Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion sorts/intro_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,8 @@ def intro_sort[T: Comparable](
"""
while end - start > size_threshold:
if max_depth == 0:
return heap_sort(array)
array[start:end] = heap_sort(array[start:end])
return array
max_depth -= 1
pivot = median_of_3(array, start, start + ((end - start) // 2) + 1, end - 1)
p = partition(array, start, end, pivot)
Expand Down
12 changes: 12 additions & 0 deletions tests/test_sorts.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from sorts.gnome_sort import gnome_sort
from sorts.heap_sort import heap_sort
from sorts.insertion_sort import insertion_sort
from sorts.intro_sort import intro_sort as intro_sort_range
from sorts.intro_sort import sort as intro_sort
from sorts.iterative_merge_sort import iter_merge_sort
from sorts.merge_insertion_sort import merge_insertion_sort
Expand Down Expand Up @@ -63,6 +64,17 @@ def test_heap_sort() -> None:
assert heap_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]


@pytest.mark.parametrize("max_depth", [0, 1])
def test_intro_sort_heap_fallback_preserves_surrounding_items(max_depth: int) -> None:
collection = [100, *range(40, 0, -1), -100]
expected = [100, *range(1, 41), -100]

result = intro_sort_range(collection, 1, 41, 16, max_depth)

assert result is collection
assert collection == expected


SORTS = (
binary_insertion_sort,
bubble_sort_iterative,
Expand Down
Loading