MinHeap

#include <iostream>
const int DEFAULT_SIZE = 20;

template<typename T>
class MinHeap {
public:
  MinHeap(int sz = DEFAULT_SIZE);
  MinHeap(T arr[], int n);
  ~MinHeap() { delete[] heap; }
  bool insert(const T& x) const;
  bool remove_min(T& x);
  bool is_full() const { return currentsize == maxsize; }
  bool is_empty() const { return currentsize == 0; }
  void make_empty() { currentsize = 0; }
private:
  T *heap;
  int currentsize;
  int maxsize;
  void sift_down(int start, int m);
  void sift_up(int start);
};

template<typename T>
MinHeap<T>::MinHeap(int sz) {
  maxsize = (DEFAULT_SIZE < sz) ? sz: DEFAULT_SIZE;
  heap = new T[maxsize];
  if (!heap) {
    std::cerr << "memory alloc error !" << std::endl;
    exit(1);
  }
}

template<typename T>
MinHeap<T>::MinHeap(T arr[], int n) {
  maxsize = (DEFAULT_SIZE < n) ? n: DEFAULT_SIZE;
  heap = new T[maxsize];
  if (!heap) {
    std::cerr << "memory alloc error !" << std::endl;
    exit(1);
  }
  for (int i = 0; i < n; i++)
    heap[i] = arr[i];
  currentsize = n;
  int currentpos = (currentsize - 2) / 2; // pos need to adjust
  while (currentpos >= 0) {
    sift_down(currentpos, currentsize - 1);
    currentpos--;
  }
}

template<typename T>
void MinHeap<T>::sift_down(int start, int m) {
  int i = start;
  int j = i * 2 + 1;
  T temp = heap[i];
  while (j <= m) {
    if (j < m && heap[j] > heap[j + 1])
      j++;
    if (temp <= heap[j])
      break;
    else {
      heap[i] = heap[j];
      i = j;
      j = 2 * j + 1;
    }
  }
  heap[i] = temp;
}

template<typename T>
void MinHeap<T>::sift_up(int start) {
  int j = start;
  int i = (j - 1) / 2;
  T temp = heap[j];
  while (j > 0) {
    if (heap[i] <= temp)
      break;
    else {
      heap[j] = heap[i];
      j = i;
      i = (i - 1) / 2;
    }
  }
  heap[j] = temp;
}

template<typename T>
bool MinHeap<T>::insert(const T& x) {
  if (currentsize == maxsize) {
    std::cerr << "heap full !" << std::endl;
    return false;
  }
  heap[currentsize] = x;
  sift_up(currentsize);
  currentsize++;
  return true;
}

template<typename T>
bool MinHeap<T>::remove_min(T& x) {
  if (!currentsize) {
    std::cout << "heap empty !" << std::endl;
    return false;
  }
  x = heap[0];
  heap[0] = heap[currentsize - 1];
  currentsize--;
  sift_down(0, currentsize - 1);
  return true;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值