首页 > 代码库 > 简易版的堆的写法

简易版的堆的写法

个人认为重点写出max_heapify和parent_heapify两个函数即可,这个版本内存管理的功能显得特别简单:

#include<iostream>
#include<stdio.h>

using namespace std;

class Heap {
public:
  int size, capacity;
  int *ele;
  void max_heapify(int i,int heap[],int len){//数组从0开始   
    int l,r,largest;  
    l=2*i+1;   r=2*i+2;  
    if( l<len && heap[l]>heap[i] )  
      largest=l;  
    else  
      largest=i;  
    if( r<len && heap[r]>heap[largest] )  
      largest=r;  
    if(largest!=i){  
      swap( heap[largest],heap[i] );  
      max_heapify(largest,heap,len);  
    }  
  }
  void parent_heapify(int i,int heap[],int len){//和parent结点不断交换   
    int parent = i / 2;  
    while (heap[i] > heap[parent]) {  
      swap(heap[i], heap[parent]);  
      i = parent, parent = i / 2;  
    }  
  } 

  Heap(int capacity, int heap[], int len) {
    this->capacity = capacity, this->size = len;
    ele = heap;
    for(int i = size/2-1 ; i >= 0; i--)  
      max_heapify(i,ele,size);
  }
  bool push(int val) {
    if (size < capacity) {
      ele[size++] = val;
      parent_heapify(size - 1, ele, size);
      return true;
    }
    else
      return false;
  }
  void pop() {
    swap(ele[0], ele[size--]);
    max_heapify(0, ele, size);
  }
  int top() {
    return ele[0];
  }
};

int main() {
  int a[10] = {1,2,3,4,5,6,7};
  int len = sizeof(a) / sizeof(a[0]);
  Heap heap(10, a, 7);
  heap.pop();
  heap.push(10);

  return 0;
}