#include <iostream>
#include <cmath>
using namespace std;
class HeapFromBottom {
private:
int *heap;
int capacity;
void heapify(int nodeIndex, int heapBottom) {
int lastParentIndex = floor(heapBottom / 2);
while (nodeIndex <= lastParentIndex) {
int leftChildIndex = 2 * nodeIndex;
int maxIndex = leftChildIndex;
if ((leftChildIndex + 1 <= heapBottom) && (heap[leftChildIndex + 1] > heap[leftChildIndex])) {
maxIndex = leftChildIndex + 1;
}
if (heap[nodeIndex] < heap[maxIndex]) {
int temp = heap[nodeIndex];
heap[nodeIndex] = heap[maxIndex];
heap[maxIndex] = temp;
nodeIndex = maxIndex;
} else {
break;
}
}
}
public:
HeapFromBottom(int arr[], int length) {
heap = new int[length + 1];
capacity = length;
for (int i = 0; i < length; ++i) {
heap[i + 1] = arr[i];
}
int lastParentIndex = floor(length / 2);
for (int i = lastParentIndex; i >= 1; --i) {
heapify(i, capacity);
}
}
~HeapFromBottom() {
delete[] heap;
}
void sort() {
int heapTop = 1;
int heapBottom = capacity;
while (heapTop < heapBottom) {
int temp = heap[heapTop];
heap[heapTop] = heap[heapBottom];
heap[heapBottom] = temp;
--heapBottom;
heapify(heapTop, heapBottom);
}
}
void print() {
for (int i = 1; i < capacity + 1; ++i) {
cout << heap[i] << " ";
}
cout << endl;
}
};
int main() {
int arr[] = {2, 9, 7, 6, 5, 8};
HeapFromBottom *heap = new HeapFromBottom(arr, sizeof(arr) / sizeof(int));
cout << "初始堆数组: ";
heap->print();
heap->sort();
cout << "堆排序后的数组: ";
heap->print();
delete heap;
return 0;
}