编辑代码

#include <iostream>
#include <cmath>

using namespace std;

class Heap {
	private:
		int *heap;
		int capacity;
		
		void heapify() {
			
			int lastParentPos = floor(capacity/2);
			
			for(int i = lastParentPos; i >= 0; --i) {
				int parentPos = i;
				
				// 保证当前的节点是父亲节点,父亲节点才有堆化的意义 
				while(parentPos  <= lastParentPos) {
					// 找出左右子节点较大的哪个节点 
					int childPos = 2 * parentPos;
					int maxPos = childPos;
					
					//比较左右子节点谁大(保证有右子节点) 
					if ((childPos + 1 <= capacity) && heap[childPos + 1] > heap[maxPos]) {
						maxPos = childPos + 1;
					}
					
					//与父节点进行比较
					if (heap[maxPos] > heap[parentPos]) {
						int temp = heap[maxPos];
						heap[maxPos] = heap[parentPos];
						heap[parentPos] = temp;
						
						parentPos = maxPos;
					}
					else {
						//父节点比子节点大,已经堆化好了 
						break;
					} 
				}
			}
		} 
	public:
		
		 Heap(int arr[], int length) {
		 	capacity = length;
		 	heap = new int[capacity + 1];
		 	
		 	for (int i = 0; i < length; ++i) {
		 		heap[i+1] = arr[i];
			 }
			 
			 heapify(); 
		 	
		 }
		 
		 print() {
		 	
		    for (int i = 1; i <= capacity; ++i) {
		 		cout << heap[i]<< " ";
			}
			cout << endl;
		 }
};

int main() {
	int arr[] = {2, 9, 7, 6, 5, 8};
	Heap *heap = new Heap(arr, sizeof(arr)/sizeof(int));
	heap->print();
	
	delete heap;
}