Skip to content

Commit c31d9e9

Browse files
committed
Add heap sort
1 parent 0394d30 commit c31d9e9

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

learn/python/day4/part2.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,29 @@ def merge_sort(a):
5353
m1 = merge_sort(a[:len(a)//2])
5454
m2 = merge_sort(a[len(a)//2:])
5555
return merge(m1,m2)
56+
57+
def heap_sort(a):
58+
def heapify():
59+
for i in range(l//2-1,-1,-1):
60+
m = a[i]
61+
if i * 2 + 2 <= l-1:
62+
m = max(m, a[i * 2 + 1], a[i * 2 + 2])
63+
else:
64+
m = max(m,a[i * 2 + 1])
65+
if m == a[i * 2 + 1]:
66+
a[i],a[i * 2 + 1] = a[i * 2 + 1],a[i]
67+
elif i * 2 + 2 <= l-1 and m == a[i * 2 + 2]:
68+
a[i], a[i * 2 + 2] = a[i * 2 + 2],a[i]
69+
l = len(a)
70+
for i in range(len(a)-1):
71+
heapify()
72+
a[0],a[l-1] = a[l-1],a[0]
73+
l -= 1
5674

5775
def solution(input):
58-
d = [i for i in range(100)]
76+
d = [i for i in range(10000)]
5977
shuffle(d)
6078
d1 = d.copy()
6179
d.sort()
62-
d1 = merge_sort(d1)
80+
heap_sort(d1)
6381
return str(d1 == d)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy