Skip to content

Commit 360ed97

Browse files
author
stuffacc
committed
Heap Sort Task
1 parent 6ca2996 commit 360ed97

File tree

2 files changed

+106
-0
lines changed

2 files changed

+106
-0
lines changed

src/5/heap_sort.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
def max_heap(arr, n, parent_id):
2+
largest = parent_id
3+
left_child = 2 * largest + 1
4+
right_child = 2 * largest + 2
5+
6+
if left_child < n and arr[left_child] > arr[largest]:
7+
largest = left_child
8+
9+
if right_child < n and arr[right_child] > arr[largest]:
10+
largest = right_child
11+
12+
if largest != parent_id:
13+
arr[parent_id], arr[largest] = arr[largest], arr[parent_id]
14+
max_heap(arr, n, largest)
15+
16+
17+
def heap_sort(arr):
18+
for i in range(len(arr) // 2 - 1, -1, -1):
19+
max_heap(arr, len(arr), i)
20+
21+
end = len(arr)
22+
for i in range(end - 1, -1, -1):
23+
arr[0], arr[i] = arr[i], arr[0]
24+
max_heap(arr, i, 0)
25+
26+
27+
arr = [4, 10, 3, 5, 1, 10, 4, 23, 2, 3, 2, 24, -1, -51, -1, 25]
28+
29+
print(arr)
30+
heap_sort(arr)
31+
print(arr)
32+

src/5/test_heap_sort.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import random
2+
import pytest
3+
from heap_sort import heap_sort
4+
5+
6+
@pytest.fixture
7+
def random_arr():
8+
random_size = random.randint(0, 1000)
9+
10+
arr = [random.randint(-1000, 1000) for _ in range(random_size)]
11+
12+
return arr
13+
14+
15+
def test_empty_array():
16+
arr = []
17+
heap_sort(arr)
18+
19+
assert arr == []
20+
21+
22+
def test_single_element():
23+
arr = [42]
24+
heap_sort(arr)
25+
26+
assert arr == [42]
27+
28+
29+
def test_sorted_array():
30+
arr = [1, 2, 3, 4, 5]
31+
heap_sort(arr)
32+
33+
assert arr == [1, 2, 3, 4, 5]
34+
35+
36+
def test_reverse_sorted_array():
37+
arr = [5, 4, 3, 2, 1]
38+
heap_sort(arr)
39+
40+
assert arr == [1, 2, 3, 4, 5]
41+
42+
43+
def test_duplicate_elements():
44+
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
45+
heap_sort(arr)
46+
47+
assert arr == [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
48+
49+
50+
def test_negative_numbers():
51+
arr = [5, -2, 0, -8, 3, 1, -1]
52+
heap_sort(arr)
53+
54+
assert arr == [-8, -2, -1, 0, 1, 3, 5]
55+
56+
57+
def test_all_identical():
58+
arr = [7, 7, 7, 7, 7]
59+
heap_sort(arr)
60+
61+
assert arr == [7, 7, 7, 7, 7]
62+
63+
64+
def test_random_with_build_in_sort(random_arr):
65+
random_arr2 = random_arr.copy()
66+
67+
heap_sort(random_arr)
68+
random_arr2.sort()
69+
70+
assert random_arr == random_arr2
71+
72+
73+
if __name__ == '__main__':
74+
pytest.main()

0 commit comments

Comments
 (0)