Skip to content
Merged
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
4 changes: 2 additions & 2 deletions .github/workflows/pytest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ jobs:
pip install -r requirements.txt
- name: Test with pytest
run: |
pip install pytest pytest-cov
pytest tests.py --doctest-modules --junitxml=junit/test-results.xml --cov=com --cov-report=xml --cov-report=html
pip install pytest
pytest
26 changes: 26 additions & 0 deletions src/heapsort/heapsort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
def heapify(nums, heap_size, root_index):
largest = root_index
left_child = (2 * root_index) + 1
right_child = (2 * root_index) + 2


if left_child < heap_size and nums[left_child] > nums[largest]:
largest = left_child

if right_child < heap_size and nums[right_child] > nums[largest]:
largest = right_child

if largest != root_index:
nums[root_index], nums[largest] = nums[largest], nums[root_index]
heapify(nums, heap_size, largest)

def heap_sort(nums):
n = len(nums)

for i in range(n, -1, -1):
heapify(nums, n, i)

for i in range(n - 1, 0, -1):
nums[i], nums[0] = nums[0], nums[i]
heapify(nums, i, 0)
return nums
42 changes: 42 additions & 0 deletions src/heapsort/heapsort_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from heapsort import heap_sort
import pytest
import random


@pytest.fixture
def random_list():
rand_list = random.randint(1, 100)
random_delta = random.randint(0, 10000)
rand_list = list(range(random_delta, rand_list + random_delta))
random.shuffle(rand_list)
return rand_list

@pytest.mark.parametrize(
["n", "expected"],
[([1], [1]),
([2, 7, 4, 8, 6, 5], [2, 4, 5, 6, 7, 8]),
([], []),
([9, 8, 7, 6, 5, 4, 3, 2, 1], [1, 2, 3, 4, 5, 6, 7, 8, 9]),
([1, 3, 2, 3, 1], [1, 1, 2, 3, 3])]
)
def test_heapsort_main(n, expected):
assert heap_sort(n) == expected

def test_heapsort_random(random_list):
assert heap_sort(random_list) == list(sorted(random_list))

rand_tests = []
for i in range(10):
rand_list = random.randint(1, 100)
random_delta = random.randint(0, 10000)
rand_list = list(range(random_delta, rand_list + random_delta))
random.shuffle(rand_list)
tup = (rand_list, sorted(rand_list))
rand_tests.append(tup)

@pytest.mark.parametrize(
["n", "expected"],
rand_tests
)
def test_heapsort_random_multiple(n, expected):
assert heap_sort(n) == expected