# 算法导论第六章堆排序——Python实现

#堆排序

# 维护最大堆的性质
def max_heapify(A, i, heap_size):
l = 2*i+1
r = 2*i+2
if l <= heap_size-1 and A[l] > A[i]:
largest = l
else:
largest = i
if r <= heap_size-1 and A[r] > A[largest]:
largest = r
if largest != i:
temp = A[i]
A[i] = A[largest]
A[largest] = temp
max_heapify(A, largest, heap_size)

def build_max_heap(A):  # 建堆
heap_size = len(A)
for i in range((heap_size-2)//2, -1, -1):  # 遍历非叶子节点
max_heapify(A, i, heap_size)

def heapsort(A):
build_max_heap(A)  # O(n)
length = len(A)
heap_size = length
for i in range(length-1, 0, -1):
temp = A[0]
A[0] = A[i]
A[i] = temp
heap_size = heap_size - 1
max_heapify(A, 0, heap_size)

A = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7]
heapsort(A)
print(A)


#最大优先队列

# 最大优先队列
def heap_maximum(A):  # 返回堆中最大元素
return A[0]

def heap_extract_max(A, heap_size):  # 去掉并返回堆中最大元素
if heap_size < 1:
print("heap underflow")
else:
max_element = A[0]
A[0] = A[heap_size - 1]
heap_size = heap_size - 1
max_heapify(A, 0, heap_size)
return max_element

def heap_increase_key(A, i, key):  # A[i] = k, k必须大于A[i]
if key < A[i]:
print("new key is smaller than current key")
else:
A[i] = key
parent = (i-1)//2
while i > 0 and A[parent] < A[i]:
temp = A[i]
A[i] = A[parent]
A[parent] = temp
i = parent

def max_heap_insert(A, key):  # 在堆中插入key
length = len(A)
heap_size = length + 1
A[heap_size - 1] = -float("inf")
heap_increase_key(A, heap_size-1, key)

def heap_delete(A, i):  # 删除元素
heap_size = len(A)
temp = A[i]
A[i] = A[heap_size-1]
A[heap_size-1] = temp
heap_size = heap_size - 1
key = A[i]
if key <= A[(i-1)//2]:
max_heapify(A, i, heap_size)
else:
while i > 1 and A[(i-1)//2] < key:
temp = A[i]
A[i] = A[(i-1)//2]
A[(i-1)//2] = temp
i = (i-1)//2

A = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7]
print(A)


01-31 15

09-11 154

05-19 17

08-28 89

05-02 47

03-09 251

08-03 174

02-02 216

04-05 3187

07-29 54

10-06 106

08-27 1118

07-14 1129

10-13 215

08-18 354

01-11 57

05-06 400

05-12 179

04-13 34

04-14 60万+

03-13 15万+

02-19 18万+

03-01 14万+

03-04 14万+

03-06 4144

03-08 7万+

04-25 7万+

03-10 13万+

03-10 19万+

03-12 11万+

#### 如果你是老板，你会不会踢了这样的员工？

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客