#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Heap {
private:
int length;
int heap_size;
int* A;
public:
Heap(vector<int>);
~Heap() { delete []A; }
int parent(int i) { return i / 2; }
int left(int i) { return 2 * i; }
int right(int i) { return 2 * i + 1; }
void max_heapify(int choice);
void build_heap();
void heap_sort();
};
Heap::Heap(vector<int> v) : length{static_cast<int>(v.size())}, heap_size{length} {
A = new int[length];
int index {};
for_each(v.begin(), v.end(), [=](int x)mutable{ A[index++] = x; });
}
void Heap::max_heapify(int choice) {
int left_son = left(choice);
int right_son = right(choice);
int largest {};
if(left_son < heap_size && A[choice] < A[left_son]) {
largest = left_son;
}
else {
largest = choice;
}
if(right_son < heap_size && A[largest] < A[right_son]) {
largest = right_son;
}
if(largest != choice) {
swap(A[largest], A[choice]);
max_heapify(largest);
}
}
void Heap::build_heap() {
for(int i = heap_size / 2; i >= 0; --i) {
max_heapify(i);
}
}
void Heap::heap_sort() {
build_heap();
for(int i = heap_size - 1; i >= 1; --i) {
cout << A[0] << " ";
swap(A[0], A[i]);
heap_size--;
max_heapify(0);
}
cout << A[0] << endl;
}
int main(int argc, const char * argv[]) {
vector<int> v;
int element {};
cout << "please input the elements you want to heap_sort :" << endl;
while(cin >> element) {
v.push_back(element);
}
Heap h {v};
cout << "the result is :" << endl;
h.heap_sort();
return 0;
}