#include <iostream>
using namespace std;
#define MAXSIZE 100
class BinaryHeap {
private:
int values[MAXSIZE];
int size{0};
bool cmp(int left, int right) {
return left < right;
}
int parentIndex(int index) {
return (index - 1) >> 1;
}
int leftSonIndex(int index) {
return ((index + 1) << 1) - 1;
}
int rightSonIndex(int index) {
return (index + 1) << 1;
}
public:
BinaryHeap() {
memset(values, 0, sizeof(values));
size = 0;
}
void push(int key) {
int pivot;
size++;
for (pivot = size - 1; pivot > 0; pivot = (pivot - 1) >> 1) {
if (cmp(key, values[parentIndex(pivot)])) {
values[pivot] = values[parentIndex(pivot)];
} else {
break;
}
}
values[pivot] = key;
}
bool empty() {
return size == 0;
}
int top() {
if (!empty()) {
return values[0];
}
return -1;
}
void pop() {
if (!empty()) {
int pivot, tmp;
size--;
for (pivot = 0; leftSonIndex(pivot) < size; ) {
tmp = (rightSonIndex(pivot) <= size &&
cmp(values[rightSonIndex(pivot)],
values[leftSonIndex(pivot)])
) ? rightSonIndex(pivot) : leftSonIndex(pivot);
if (cmp(values[tmp], values[size])) {
values[pivot] = values[tmp];
pivot = tmp;
} else {
break;
}
}
values[pivot] = values[size];
}
}
};
int main() {
BinaryHeap heap;
int size = 10;
for (int i = 0; i < size; ++i) {
heap.push(i);
}
for (int j = 0; j < size; ++j) {
cout << heap.top();
heap.pop();
}
return 0;
}
[算法]二叉堆
最新推荐文章于 2018-01-20 18:22:26 发布