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
17 changes: 17 additions & 0 deletions .github/workflows/simple-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# .github/workflows/simple-test.yml
name: Simple Test

on:
push:
branches: [ heap_sort ]

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
with:
python-version: '3.12.3'
- run: pip install pytest
- run: pytest test_heap_sort.py -v
32 changes: 32 additions & 0 deletions src/5/heap_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
def max_heap(arr, n, parent_id):
largest = parent_id
left_child = 2 * largest + 1
right_child = 2 * largest + 2

if left_child < n and arr[left_child] > arr[largest]:
largest = left_child

if right_child < n and arr[right_child] > arr[largest]:
largest = right_child

if largest != parent_id:
arr[parent_id], arr[largest] = arr[largest], arr[parent_id]
max_heap(arr, n, largest)


def heap_sort(arr):
for i in range(len(arr) // 2 - 1, -1, -1):
max_heap(arr, len(arr), i)

end = len(arr)
for i in range(end - 1, -1, -1):
arr[0], arr[i] = arr[i], arr[0]
max_heap(arr, i, 0)


arr = [4, 10, 3, 5, 1, 10, 4, 23, 2, 3, 2, 24, -1, -51, -1, 25]

print(arr)
heap_sort(arr)
print(arr)

74 changes: 74 additions & 0 deletions src/5/test_heap_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import random
import pytest
from heap_sort import heap_sort


@pytest.fixture
def random_arr():
random_size = random.randint(0, 1000)

arr = [random.randint(-1000, 1000) for _ in range(random_size)]

return arr


def test_empty_array():
arr = []
heap_sort(arr)

assert arr == []


def test_single_element():
arr = [42]
heap_sort(arr)

assert arr == [42]


def test_sorted_array():
arr = [1, 2, 3, 4, 5]
heap_sort(arr)

assert arr == [1, 2, 3, 4, 5]


def test_reverse_sorted_array():
arr = [5, 4, 3, 2, 1]
heap_sort(arr)

assert arr == [1, 2, 3, 4, 5]


def test_duplicate_elements():
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
heap_sort(arr)

assert arr == [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]


def test_negative_numbers():
arr = [5, -2, 0, -8, 3, 1, -1]
heap_sort(arr)

assert arr == [-8, -2, -1, 0, 1, 3, 5]


def test_all_identical():
arr = [7, 7, 7, 7, 7]
heap_sort(arr)

assert arr == [7, 7, 7, 7, 7]


def test_random_with_build_in_sort(random_arr):
random_arr2 = random_arr.copy()

heap_sort(random_arr)
random_arr2.sort()

assert random_arr == random_arr2


if __name__ == '__main__':
pytest.main()