核心算法
shiftUp()
shiftDown()
完整代码(C++)
#include <iostream>
#include <vector>
#define n 10
using namespace std;
template<typename T>
class MaxHeap {
private:
T *data;
int count;
int capacity;
void shiftUp(int k) {
while (k > 1) {
if (data[k / 2] < data[k]) {
swap(data[k / 2], data[k]);
}
k = k / 2;
}
}
void shiftDown(int k) {
while (2 * k <= count) {
int j = 2 * k;
if (j + 1 <= count && data[j + 1] > data[j]) {
j += 1;
}
if (data[k] >= data[j]) {
break;
}
swap(data[k], data[j]);
k = j;
}
}
public:
MaxHeap(int c) {
data = new T[c];
count = 0;
capacity = n;
}
bool empty() {
return count == 0;
}
int size() {
return count;
}
void insert(T k) {
if (count == capacity) {
cout << "越界" << endl;
return;
}
data[++count] = k;
shiftUp(count);
}
void show() {
for (int i = 1; i <= count; ++i) {
cout << data[i] << " ";
}
cout << endl;
}
T ex() {
if (count == 0) {
cout << "空了" << endl;
return -1;
}
T res = data[1];
swap(data[1], data[count]);
count--;
shiftDown(1);
// show();
return res;
}
};
template<typename T>
void show(vector<T> arr) {
for (int i = 0; i < arr.size(); ++i) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
vector<int> arr;
srand(time(NULL));
for (int i = 0; i < n; ++i) {
arr.push_back(rand() % 100);
}
show(arr);
MaxHeap<int> maxHeap(arr.size() + 1);
for (int i = 0; i < arr.size(); ++i) {
maxHeap.insert(arr[i]);
}
maxHeap.show();
for (int i = arr.size() - 1; i >= 0; --i) {
arr[i] = maxHeap.ex();
}
show(arr);
return 0;
}