Skip to content

Commit bde4f18

Browse files
Add files via upload
1 parent aa0b082 commit bde4f18

File tree

2 files changed

+671
-0
lines changed

2 files changed

+671
-0
lines changed

max_heap.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
sorted_array = list()
2+
def max_heapify(arr, i, heap_size):
3+
left = 2*i-1
4+
right = 2*i+1-1
5+
max_ = i-1
6+
if (left<heap_size and arr[i-1]<arr[left]):
7+
max_ = left
8+
else:
9+
max_ = i-1
10+
if (right<heap_size and arr[max_]<arr[right]):
11+
max_ = right
12+
if (max_ != i-1):
13+
arr[max_], arr[i-1] = arr[i-1], arr[max_]
14+
res = max_heapify(arr, max_+1, heap_size)
15+
# print("res", res) : will return the below line whenever
16+
# a recursive call is completed.
17+
return ("max_heapify arr:{}".format(arr))
18+
19+
20+
def build_max_heap(arr):
21+
heap_size = len(arr)
22+
for i in range(len(arr)//2, 0, -1):
23+
array = max_heapify(arr, i, heap_size)
24+
print("build_max_heap", arr)
25+
return arr
26+
27+
28+
def extract_heap(arr):
29+
if len(arr)<1:
30+
return "No Elements"
31+
max_ = arr[0]
32+
sorted_array.append(max_)
33+
arr[0] = arr[len(arr)-1]
34+
del arr[len(arr)-1]
35+
max_heapify(arr, 1, len(arr))
36+
return (arr, max_)
37+
38+
def heap_sort(arr):
39+
array = build_max_heap(arr)
40+
for i in range(len(array)):
41+
print("heap_sort", extract_heap(array))
42+
print(sorted_array)
43+
44+
45+

0 commit comments

Comments
 (0)