Skip to content

Commit a88bcf5

Browse files
Create Improved Heap sorting technique TheAlgorithms#9528
In this adjusted version, the code is slightly more concise while maintaining readability. The changes include simplifying the conditional statements and loop ranges.
1 parent 821dae5 commit a88bcf5

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Diff for: Improved Heap sorting technique #9528

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
def heapify(arr, n, i):
2+
largest = i
3+
left = 2 * i + 1
4+
right = 2 * i + 2
5+
6+
if left < n and arr[left] > arr[largest]:
7+
largest = left
8+
9+
if right < n and arr[right] > arr[largest]:
10+
largest = right
11+
12+
if largest != i:
13+
arr[i], arr[largest] = arr[largest], arr[i]
14+
heapify(arr, n, largest)
15+
16+
def heap_sort(arr):
17+
n = len(arr)
18+
19+
for i in range(n // 2 - 1, -1, -1):
20+
heapify(arr, n, i)
21+
22+
for i in range(n - 1, 0, -1):
23+
arr[i], arr[0] = arr[0], arr[i]
24+
heapify(arr, i, 0)
25+
26+
# Example Usage
27+
arr = [12, 11, 13, 5, 6, 7]
28+
heap_sort(arr)
29+
print("Sorted array:", arr)

0 commit comments

Comments
 (0)