MinHeap

来源:互联网 发布:软件项目经理培训视频 编辑:程序博客网 时间:2024/05/16 05:46
#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;}

原创粉丝点击