Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add some documentation for heap sort #9949

Merged
merged 5 commits into from
Dec 31, 2024
Merged
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
47 changes: 28 additions & 19 deletions sorts/heap_sort.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
"""
This is a pure Python implementation of the heap sort algorithm.

For doctests run following command:
python -m doctest -v heap_sort.py
or
python3 -m doctest -v heap_sort.py

For manual testing run:
python heap_sort.py
A pure Python implementation of the heap sort algorithm.
"""


def heapify(unsorted, index, heap_size):
def heapify(unsorted: list[int], index: int, heap_size: int) -> None:
"""
:param unsorted: unsorted list containing integers numbers
:param index: index
:param heap_size: size of the heap
:return: None
>>> unsorted = [1, 4, 3, 5, 2]
>>> heapify(unsorted, 0, len(unsorted))
>>> unsorted
[4, 5, 3, 1, 2]
>>> heapify(unsorted, 0, len(unsorted))
>>> unsorted
[5, 4, 3, 1, 2]
"""
largest = index
left_index = 2 * index + 1
right_index = 2 * index + 2
Expand All @@ -22,26 +27,26 @@ def heapify(unsorted, index, heap_size):
largest = right_index

if largest != index:
unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest]
unsorted[largest], unsorted[index] = (unsorted[index], unsorted[largest])
heapify(unsorted, largest, heap_size)


def heap_sort(unsorted):
def heap_sort(unsorted: list[int]) -> list[int]:
"""
Pure implementation of the heap sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
A pure Python implementation of the heap sort algorithm

:param collection: a mutable ordered collection of heterogeneous comparable items
:return: the same collection ordered by ascending

Examples:
>>> heap_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]

>>> heap_sort([])
[]

>>> heap_sort([-2, -5, -45])
[-45, -5, -2]
>>> heap_sort([3, 7, 9, 28, 123, -5, 8, -30, -200, 0, 4])
[-200, -30, -5, 0, 3, 4, 7, 8, 9, 28, 123]
"""
n = len(unsorted)
for i in range(n // 2 - 1, -1, -1):
Expand All @@ -53,6 +58,10 @@ def heap_sort(unsorted):


if __name__ == "__main__":
import doctest

doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(heap_sort(unsorted))
if user_input:
unsorted = [int(item) for item in user_input.split(",")]
print(f"{heap_sort(unsorted) = }")