diff --git a/.github/workflows/simple-test.yml b/.github/workflows/simple-test.yml new file mode 100644 index 0000000..4c8d84a --- /dev/null +++ b/.github/workflows/simple-test.yml @@ -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 \ No newline at end of file diff --git a/src/5/heap_sort.py b/src/5/heap_sort.py new file mode 100755 index 0000000..e6426ce --- /dev/null +++ b/src/5/heap_sort.py @@ -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) + diff --git a/src/5/test_heap_sort.py b/src/5/test_heap_sort.py new file mode 100755 index 0000000..247f04c --- /dev/null +++ b/src/5/test_heap_sort.py @@ -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()