Max Heapify in C++
Max heapify using std::vector
#include <iostream>
#include <vector>
using namespace std;
void swap(vector<int>& heap, int i, int j)
{
int t= heap[i];
heap[i]= heap[j];
heap[j]= t;
}
void maxHeapify(vector<int>& heap, int i)
{
int left= (i+1)*2-1;
int right= (i+1)*2;
int largest= i;
int heapSize= heap.size();
if (left < heapSize && heap[left] > heap[largest]) largest= left;
if (right < heapSize && heap[right] > heap[largest]) largest= right;
if (i != largest)
{
swap(heap, largest, i);
maxHeapify(heap, largest);
}
}
void maxHeapify(vector<int>& heap)
{
int heapSize= heap.size();
if (heapSize <= 0) return;
for (int i= heapSize-1; i >= 0; --i)
maxHeapify(heap, i);
}
int main()
{
vector<int> heap;
for (int i= 0; i < 10; ++i) heap.push_back(i);
maxHeapify(heap);
for (int i= 0; i < heap.size(); ++i)
cout << heap[i] << endl;
}
Max heapify using std::array
#include <iostream>
#include <array>
using namespace std;
template<size_t SZ>
void swap(array<int,SZ>& heap, int i, int j)
{
int t= heap[i];
heap[i]= heap[j];
heap[j]= t;
}
template<size_t SZ>
void maxHeapify(array<int,SZ>& heap, int i)
{
int left= (i+1)*2-1;
int right= (i+1)*2;
int largest= i;
int heapSize= heap.size();
if (left < heapSize && heap[left] > heap[largest]) largest= left;
if (right < heapSize && heap[right] > heap[largest]) largest= right;
if (i != largest)
{
swap(heap, largest, i);
maxHeapify(heap, largest);
}
}
template<size_t SZ>
void maxHeapify(array<int,SZ>& heap)
{
int heapSize= heap.size();
cout << "heapSize: " << heapSize << endl;
if (heapSize <= 0) return;
for (int i= heapSize-1; i >= 0; --i)
maxHeapify(heap, i);
}
int main()
{
array<int,10> heap;
for (int i= 0; i < 10; ++i) heap[i]= i;
maxHeapify(heap);
for (int i= 0; i < heap.size(); ++i)
cout << heap[i] << endl;
}