最近在自学数据结构,写了个最大堆模板,heap的大小到时候用malloc动态申请

int heapsize, *heap;
void up(int x){//自下而上调整堆 
    while(x != 1){
        if(heap[x>>1] < heap[x]){
            swap(heap[x>>1], heap[x]);
            x >>= 1;
        }
        else break;
    }
} 
void down(int x){//自上而下调整堆 
    int y = x<<1;
    while(y <= heapsize){
        if(y < heapsize && heap[y] < heap[y+1])
            y++;
        if(heap[y] > heap[x]){
            swap(heap[y], heap[x]);
            x = y, y = x<<1;
        }    
        else break;
    }
}
void pop(){//取出堆顶元素 
    heap[1] = heap[heapsize--];
    down(1);
}
void push(int x){//增加新元素
    heap[++heapsize] = x;
    up(heapsize);
}
void build(){//建立堆 
    for(int i = 1; i <= heapsize; i++) up(i);
}
View Code
原文地址:https://www.cnblogs.com/xiaohongmao/p/2547439.html