1 #include<stdio.h> 2 #include<malloc.h> 3 void shift_down(int a[], int low, int high) 4 { 5 int i = low, j = i*2; 6 int tmp = a[i]; 7 while(j <= high){ 8 if(j < high && a[j] < a[j+1]) 9 j++; 10 if(tmp < a[j]){ 11 a[i] = a[j]; 12 i = j; 13 j = i*2; 14 } 15 else break; 16 } 17 a[i] = tmp; 18 } 19 void shift_up(int a[], int low, int high) 20 { 21 int i = high/2, j = high; 22 int tmp = a[high]; 23 while(i >= 1){ 24 if(a[i] < tmp){ 25 a[j] = a[i]; 26 j = i; 27 i = j/2; 28 } 29 else break; 30 } 31 a[j] = tmp; 32 } 33 void print(int a[], int n) 34 { 35 int i; 36 for(i = 1; i <= n; i++){ 37 printf("%d ", a[i]); 38 } 39 printf(" "); 40 } 41 int main() 42 { 43 int n, i, a[110]; 44 scanf("%d", &n); 45 for(i = 1; i <= n; i++){ 46 scanf("%d", &a[i]); 47 } 48 for(i = n/2; i >= 1; i--){ 49 shift_down(a, i, n); 50 } //建立大顶堆 51 print(a, n); 52 53 printf("删除大顶堆顶:"); 54 a[1] = a[n];//删除当前最大元素 55 n--; 56 shift_down(a, 1, n); 57 print(a, n); 58 59 printf("插入一个值:"); 60 n++; 61 scanf("%d", &a[n]); 62 shift_up(a, 1, n); 63 print(a, n); 64 return 0; 65 } 66 /*10 67 6 8 7 9 0 1 3 2 4 5*/