Skip to content

Commit 00aa6bd

Browse files
Merge pull request #210 from Abhi8756/feature/heap-sort-python
Add Heap Sort implementation in Python
2 parents 6db955a + b166a35 commit 00aa6bd

1 file changed

Lines changed: 105 additions & 0 deletions

File tree

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
"""
2+
Algorithm: Heap Sort
3+
Description: Comparison-based sorting algorithm using binary heap data structure
4+
Time Complexity: O(n log n) for all cases
5+
Space Complexity: O(1) auxiliary space
6+
Author: Abhijit
7+
"""
8+
9+
def heapify(arr, n, i):
10+
"""
11+
Heapify a subtree rooted with node i.
12+
13+
Args:
14+
arr: Array to heapify
15+
n: Size of heap
16+
i: Root index of subtree to heapify
17+
"""
18+
largest = i
19+
left = 2 * i + 1
20+
right = 2 * i + 2
21+
22+
if left < n and arr[left] > arr[largest]:
23+
largest = left
24+
25+
if right < n and arr[right] > arr[largest]:
26+
largest = right
27+
28+
if largest != i:
29+
arr[i], arr[largest] = arr[largest], arr[i]
30+
heapify(arr, n, largest)
31+
32+
33+
def heap_sort(input_data):
34+
"""
35+
Sorts an array using heap sort algorithm.
36+
37+
Args:
38+
input_data: List of comparable elements to sort
39+
40+
Returns:
41+
List: Sorted array in ascending order
42+
43+
Raises:
44+
ValueError: When input is invalid
45+
TypeError: When input is not a list
46+
"""
47+
if input_data is None:
48+
raise ValueError("Input cannot be None")
49+
50+
if not isinstance(input_data, list):
51+
raise TypeError("Input must be a list")
52+
53+
if not input_data:
54+
return []
55+
56+
# Create a copy to avoid modifying original
57+
arr = input_data.copy()
58+
n = len(arr)
59+
60+
# Build max heap
61+
for i in range(n // 2 - 1, -1, -1):
62+
heapify(arr, n, i)
63+
64+
# Extract elements from heap one by one
65+
for i in range(n - 1, 0, -1):
66+
arr[0], arr[i] = arr[i], arr[0]
67+
heapify(arr, i, 0)
68+
69+
return arr
70+
71+
72+
def main():
73+
"""Test the algorithm with example cases."""
74+
# Test Case 1
75+
test_data = [64, 34, 25, 12, 22, 11, 90]
76+
result = heap_sort(test_data)
77+
print(f"Original: {test_data}")
78+
print(f"Sorted: {result}")
79+
80+
# Test Case 2 - Edge case
81+
edge_case = []
82+
try:
83+
result = heap_sort(edge_case)
84+
print(f"Empty array result: {result}")
85+
except ValueError as e:
86+
print(f"Handled edge case: {e}")
87+
88+
# Test Case 3 - Single element
89+
single_element = [42]
90+
result = heap_sort(single_element)
91+
print(f"Single element: {single_element} -> {result}")
92+
93+
# Test Case 4 - Already sorted
94+
sorted_array = [1, 2, 3, 4, 5]
95+
result = heap_sort(sorted_array)
96+
print(f"Already sorted: {sorted_array} -> {result}")
97+
98+
# Test Case 5 - Reverse sorted
99+
reverse_sorted = [5, 4, 3, 2, 1]
100+
result = heap_sort(reverse_sorted)
101+
print(f"Reverse sorted: {reverse_sorted} -> {result}")
102+
103+
104+
if __name__ == "__main__":
105+
main()

0 commit comments

Comments
 (0)