首页 > 代码库 > 堆结构与堆排序
堆结构与堆排序
#ifndef HEAP_H #define HEAP_H #include <iostream> #include <vector> using namespace std; template <typename T> class Heap { public: Heap(vector<T> &_vec) : vec(_vec){} ~Heap(){ vec.~vector(); } Heap(const Heap& rhs) { this->vec = rhs.vec; } Heap &operator =(const Heap&rhs) { if(this == &rhs) return *this; vec.clear(); this->vec = rhs.vec; return *this; } void heapify(bool isMax,int index,int size) { int l = left(index); int r = right(index); int largest; if(isMax) { if(l < size && vec.at(l) > vec.at(index)) largest = l; else largest = index; if(r < size && vec.at(r) > vec.at(largest)) largest = r; if(largest != index) { std::swap(vec.at(index),vec.at(largest)); heapify(true,largest,size); } } else { if(l < size && vec.at(l) < vec.at(index)) largest = l; else largest = index; if(r < size && vec.at(r) < vec.at(largest)) largest = r; if(largest != index) { std::swap(vec.at(index),vec.at(largest)); heapify(false,largest,size); } } } void build_heapify(bool isMax,int size) { int _size = size; for(int i=_size/2;i>=0;i--) heapify(isMax,i,size); } void sort(bool isMax) { int size = vec.size()-1; build_heapify(isMax,size); for(int i=size;i>=0;i--) { std::swap(vec.at(0),vec.at(i)); int _size = i; heapify(isMax,0,_size); } } friend ostream& operator <<(ostream &os, const Heap<T> &heap) { for(int i=0;i<heap.vec.size();i++) { os << heap.vec.at(i) << ends; } os << endl; return os; } T &operator[](size_t n) { return vec[n]; } private: inline int left(int index) { return index*2+1; } inline int right(int index) { return index*2+2; } vector<T> &vec; }; #endif // HEAP_H
堆结构与堆排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。