#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
int parentIndex(int i)
{
return i/2;
}
int leftChildIndex(int i)
{
return 2*i;
}
int rightChildIndex(int i)
{
return 2*i + 1;
}
int maxHeapify(vector<int> &A, int index, int heapSize)
{
int leftIndex = leftChildIndex(index);
int rightIndex = rightChildIndex(index);
int largest = index;
if(leftIndex >=0 && leftIndex < heapSize && A[leftIndex] > A[largest])
{
largest = leftIndex;
}
if(rightIndex >=0 && rightIndex < heapSize && A[rightIndex] > A[largest])
{
largest = rightIndex;
}
if(largest != index)
{
int tmp = A[largest];
A[largest] = A[index];
A[index] = tmp;
maxHeapify(A, largest, heapSize);
}
return 0;
}
int buildMaxHeap(vector<int> &A)
{
int heapSize = A.size();
for(int i = heapSize/2 - 1; i > 0; i--)
{
maxHeapify(A, i, A.size());
}
return 0;
}
int heapSort(vector<int> &A)
{
buildMaxHeap(A);
#if 1
int heapSize = A.size();
for(int i = heapSize - 1; i > 0; i--)
{
int tmp = A[0];
A[0] = A[i];
A[i] = tmp;
heapSize -= 1;
maxHeapify(A,0, heapSize);
}
#endif
return 0;
}
int main()
{
vector<int> A;
A.resize(14);
A ={27, 17, 3, 16, 13, 10, 1, 5, 7, 12, 4, 8, 9, 0};
for(auto entry:A)
{
cout << entry<<endl;
}
printf("**************************\n");
#if 0
maxHeapify(A, 2, A.size());
printf("**************************\n");
for(auto entry:A)
{
cout << entry<<endl;
}
printf("**************************\n");
buildMaxHeap(A);
printf("**************************\n");
for(auto entry:A)
{
cout << entry<<endl;
}
printf("**************************\n");
#endif
heapSort(A);
for(auto entry:A)
{
cout << entry<<endl;
}
printf("**************************\n");
return 0;
}