Skip to content

Commit 65fcbea

Browse files
sorts: make heap sort support comparable items
1 parent cfc9075 commit 65fcbea

1 file changed

Lines changed: 25 additions & 7 deletions

File tree

sorts/heap_sort.py

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,16 @@
22
A pure Python implementation of the heap sort algorithm.
33
"""
44

5+
from typing import Protocol
56

6-
def heapify(unsorted: list[int], index: int, heap_size: int) -> None:
7+
8+
class Comparable(Protocol):
9+
def __lt__(self, other: object, /) -> bool: ...
10+
11+
12+
def heapify[T: Comparable](unsorted: list[T], index: int, heap_size: int) -> None:
713
"""
8-
:param unsorted: unsorted list containing integers numbers
14+
:param unsorted: unsorted list containing comparable items
915
:param index: index
1016
:param heap_size: size of the heap
1117
:return: None
@@ -20,22 +26,23 @@ def heapify(unsorted: list[int], index: int, heap_size: int) -> None:
2026
largest = index
2127
left_index = 2 * index + 1
2228
right_index = 2 * index + 2
23-
if left_index < heap_size and unsorted[left_index] > unsorted[largest]:
29+
30+
if left_index < heap_size and unsorted[largest] < unsorted[left_index]:
2431
largest = left_index
2532

26-
if right_index < heap_size and unsorted[right_index] > unsorted[largest]:
33+
if right_index < heap_size and unsorted[largest] < unsorted[right_index]:
2734
largest = right_index
2835

2936
if largest != index:
3037
unsorted[largest], unsorted[index] = (unsorted[index], unsorted[largest])
3138
heapify(unsorted, largest, heap_size)
3239

3340

34-
def heap_sort(unsorted: list[int]) -> list[int]:
41+
def heap_sort[T: Comparable](unsorted: list[T]) -> list[T]:
3542
"""
36-
A pure Python implementation of the heap sort algorithm
43+
A pure Python implementation of the heap sort algorithm.
3744
38-
:param collection: a mutable ordered collection of heterogeneous comparable items
45+
:param unsorted: a mutable collection of comparable items
3946
:return: the same collection ordered by ascending
4047
4148
Examples:
@@ -47,13 +54,24 @@ def heap_sort(unsorted: list[int]) -> list[int]:
4754
[-45, -5, -2]
4855
>>> heap_sort([3, 7, 9, 28, 123, -5, 8, -30, -200, 0, 4])
4956
[-200, -30, -5, 0, 3, 4, 7, 8, 9, 28, 123]
57+
>>> heap_sort(["banana", "apple", "cherry"])
58+
['apple', 'banana', 'cherry']
59+
>>> heap_sort([3.14, 1.5, 2.7])
60+
[1.5, 2.7, 3.14]
61+
>>> heap_sort([1, "two"]) # doctest: +ELLIPSIS
62+
Traceback (most recent call last):
63+
...
64+
TypeError: ...
5065
"""
5166
n = len(unsorted)
67+
5268
for i in range(n // 2 - 1, -1, -1):
5369
heapify(unsorted, i, n)
70+
5471
for i in range(n - 1, 0, -1):
5572
unsorted[0], unsorted[i] = unsorted[i], unsorted[0]
5673
heapify(unsorted, 0, i)
74+
5775
return unsorted
5876

5977

0 commit comments

Comments
 (0)