GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Leetcode_python/Basic Algorithm/heap.py at master · xtymichael/Leetcode_python

Expand file tree

/

heap.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
63 lines (47 loc) · 1.37 KB
/

heap.py

Copy path

File metadata and controls

63 lines (47 loc) · 1.37 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# HEAP
def max_heapify(alist, i, end):
# parent = (i - 1) / 2
left = i * 2 + 1
right = i * 2 + 2
if (left <= end and alist[left] > alist[i]):
largest = left
else:
largest = i
if (right <= end and alist[right] > alist[largest]):
largest = right
if largest != i:
alist[i], alist[largest] = alist[largest], alist[i]
max_heapify(alist, largest, end)
def build_max_heap(alist):
for i in range(len(alist)/2 - 1, -1, -1):
max_heapify(alist, i, len(alist) - 1)
def heap_sort(alist):
build_max_heap(alist)
end = len(alist) - 1
for i in range(len(alist) - 1, 0, -1):
alist[0], alist[i] = alist[i], alist[0]
end -= 1
max_heapify(alist, 0, end)
def heap_extract_max(alist):
if len(alist) < 1:
exit # 'list has no item'
maxItem = alist[0]
alist[0] = alist[len(alist) - 1]
max_heapify(alist, 0, len(alist) - 1)
alist.pop()
def heap_increase_key(alist, key, index):
if key <= alist[index]:
exit # new key is not larger
alist[index] = key
while index > 0 and alist[(index - 1) / 2] < alist[index]:
alist[index], alist[(index - 1) / 2] = alist[(index - 1) / 2], alist[index]
index = (index - 1) / 2
def max_heap_insert(alist, key):
alist.append(float('-Infinity'))
heap_increase_key(alist, key, len(alist) - 1)
sample = [54,26,93,17,77,31,44,55,20]
print sample
build_max_heap(sample)
print sample
max_heap_insert(sample, 80)
print sample
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.