Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 50355fb

Browse files
committed
Added Heap in python
1 parent 48984d1 commit 50355fb

File tree

1 file changed

+84
-0
lines changed
  • Data Structures/Heap/Python

1 file changed

+84
-0
lines changed

‎Data Structures/Heap/Python/Heap.py‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
def min_heapify(arr,n,i):
2+
"""This function will perform max heapify on elements level-wise
3+
or wil choose largest among it's left,right child and itself.
4+
Parameters:
5+
arr: List of integers.
6+
n: Length of list arr.
7+
i: index of element
8+
Returns:
9+
None
10+
"""
11+
smallest = i
12+
left = 2*i + 1
13+
right = 2*i + 2
14+
15+
if(left<n and arr[left]<arr[smallest]):
16+
smallest = left
17+
if(right<n and arr[right]<arr[smallest]):
18+
smallest = right
19+
20+
if(i!=smallest):
21+
arr[i],arr[smallest] = arr[smallest],arr[i]
22+
23+
min_heapify(arr,n,smallest)
24+
25+
26+
def max_heapify(arr,n,i):
27+
"""This function will perform max heapify on elements level-wise
28+
or wil choose largest among it's left,right child and itself.
29+
Parameters:
30+
arr: List of integers.
31+
n: Length of list arr.
32+
i: index of element
33+
Returns:
34+
None
35+
"""
36+
largest = i
37+
left = 2*i + 1
38+
right = 2*i + 2
39+
40+
if(left < n and arr[left] > arr[largest]):
41+
largest = left
42+
if(right < n and arr[right] > arr[largest]):
43+
largest = right
44+
if(i!=largest):
45+
arr[i],arr[largest] = arr[largest],arr[i]
46+
max_heapify(arr,n,largest)
47+
48+
49+
def min_build_heap(arr,n):
50+
"""This function will build min heap.
51+
Parameters:
52+
arr: List of integers.
53+
n: Length of list arr.
54+
Returns:
55+
None
56+
"""
57+
for i in range(len(arr)//2):
58+
min_heapify(arr,n,i)
59+
60+
61+
def max_build_heap(arr,n):
62+
"""This function will build max heap.
63+
Parameters:
64+
arr: List of integers.
65+
n: Length of list arr.
66+
"""
67+
for i in range(len(arr)//2):
68+
max_heapify(arr,n,i)
69+
70+
71+
def main():
72+
arr = [8,2,5,6,9]
73+
n = len(arr)
74+
print("List Before min heapify =>",arr)
75+
min_build_heap(arr,n)
76+
print("List after min heapify=>",arr)
77+
arr = [8,2,5,6,9]
78+
print("List Before min heapify =>",arr)
79+
max_build_heap(arr,n)
80+
print("List after min heapify=>",arr)
81+
82+
if __name__ == "__main__":
83+
main()
84+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /