版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Acceptedxukai/article/details/9158121
#include <iostream>
#include <cstdio>
using namespace std;
int a[100];
void swap(int &x ,int &y){
int temp;
temp = x;
x = y;
y = temp;
}
void heap_adjust(int root,int n){//max heap
int j = root << 1;
int temp = a[root];
while(j <= n){
if( j + 1 <= n && a[j] < a[j+1]) j ++;
if(a[j] <= temp) break;
else{
swap(a[j/2],a[j]);
//a[j/2] = a[j];
j <<= 1;
}
}
//a[j/2] = temp;
}
void heap_insert(int num, int k){
a[k] = num;
while(k > 1 && a[k] > a[k/2]){//max
swap(a[k],a[k/2]);
k >>= 1;
}
}
void heapsort(int n)
{
int i,temp;
for(i=n/2;i>=1;i--)
heap_adjust(i,n);
for(i=n-1;i>=1;i--)
{
temp=a[i+1];
a[i+1]=a[1];
a[1]=temp;
heap_adjust(1,i);
}
}
int main()
{
/*int i,n;
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
heapsort(n);
for(i=1;i<=n;i++)
printf("%d ",a[i]);*/
int i,n=10,m = 4,k = 0,num;
for(int i = 0 ; i < n ; i ++){
scanf("%d",&num);
k ++;
if(k <= m)
heap_insert(num,k);
else{
if(a[1] > num){
a[1] = num;
heap_adjust(1,m);
}
}
printf("a[1] = %d\n",a[1]);
}
printf("%d\n",a[1]);
return 0;
}