头文件
#ifndef _VECTOR_HEAP_
#define _VECTOR_HEAP_
#include<vector>
using std::vector;
template<class T>
class VectorMaxHeap
{
public:
VectorMaxHeap(const vector<T>& vec1);
void print()const;
void BuildMaxHeap();
void exchange(T&vec1s, T&vec2f);
void safeguardHeap(int i);
vector<T> heapSort();
private:
vector<T> vec;
int heapSize;
};
template<class T>
VectorMaxHeap<T>::VectorMaxHeap(const vector<T>& vec1) {
vec.push_back(0);
for (auto c : vec1) {
vec.push_back(c);
}
heapSize = vec.size();
BuildMaxHeap();
}
template<class T>
void VectorMaxHeap<T>::print()const {
for (auto c : vec)
cout << c << " ";
}
template<class T>
void VectorMaxHeap<T>::exchange(T&vec1s, T&vec2f) {
int tmp = vec2f;
vec2f = vec1s;
vec1s = tmp;
}
template<class T>
void VectorMaxHeap<T>::safeguardHeap(int i) {
int left = 2 * i;
int right = 2 * i + 1;
int la;
if (right<vec.size() && vec[right]>vec[i])
la = right;
else
la = i;
if (left<vec.size() && vec[left]>vec[la])
la = left;
if (la != i) {
exchange(vec[la], vec[i]);
safeguardHeap(la);
}
}
template<class T>
void VectorMaxHeap<T>::BuildMaxHeap() {
int pos = vec.size() / 2;
for (pos; pos > 0; pos--) {
safeguardHeap(pos);
}
}
#endif // !_VECTOR_HEAP_
测试
#include<iostream>
#include"VectorHeap.h"
using std::cout;
using std::cin;
int main()
{
vector<int> input;
int i;
while (cin >> i) {
input.push_back(i);
}
VectorMaxHeap<int> heap(input);
heap.print();
system("pause");
}