1 #include<iostream> 2 using namespace std; 3 4 //把a[i]中的数值增加到新的值key 5 void Heap_Increase_Key(int a[], int i, int key) 6 { 7 if (key < a[i]) 8 exit(1); 9 a[i] = key; 10 while (i>1&&a[i/2]<a[i]) 11 { 12 int t = a[i]; 13 a[i] = a[i / 2]; 14 a[i / 2] = t; 15 i = i / 2; 16 } 17 } 18 19 20 21 22 //插入一个新的值key到堆里 23 void Max_Heap_Insert(int a[], int key,int size) 24 { 25 size++; 26 a[size] = -100000;//此处应取到尽量小的数 27 Heap_Increase_Key(a, size, key); 28 } 29 30 31 //取走最大数 32 int Heap_Extract_Max(int a[],int max,int size) 33 { 34 int n = size; 35 if (n < 1) 36 exit(1); 37 int max = a[1]; 38 a[1] = a[n]; 39 size--; 40 Max_Heapify(a, 1);//Max_Heapify函数用于堆的修复 41 return max; 42 }