Just checking if I could still do it:
#include <iostream>
#include <algorithm>
std::size_t getParent(std::size_t n)
{
return (n - 1) / 2;
}
template<typename I>
void heapify(I begin, I end)
{
std::size_t size = std::distance(begin, end);
for(std::size_t loop = 1;loop < size; ++loop)
{
std::size_t current = loop;
std::size_t parent = getParent(current);
while(current != 0 && *(begin + parent) < *(begin + current))
{
std::swap(*(begin + parent), *(begin + current));
current = parent;
parent = getParent(current);
}
}
}
template<typename I>
void heapPop(I begin, I end)
{
I last = end - 1;
std::swap(*begin, *last);
std::size_t size = std::distance(begin, last);
std::size_t current = 0;
while(current < size)
{
std::size_t child1 = current * 2 + 1;
std::size_t child2 = current * 2 + 2;
std::size_t goodChild = current;
if (child2 < size)
{
goodChild = (*(begin + child1) > *(begin + child2)) ? child1 : child2;
}
else if (child1 < size)
{
goodChild = child1;
}
if (*(begin + current) < *(begin + goodChild))
{
std::swap(*(begin + current), *(begin + goodChild));
current = goodChild;
continue;
}
break;
}
}
template<typename I>
void heap_sort(I begin, I end)
{
heapify(begin, end);
while(begin != end)
{
heapPop(begin, end);
--end;
}
}
int main()
{
int data[] = {6,5,3,1,8,7,2,4};
heap_sort(std::begin(data), std::end(data));
std::copy(std::begin(data), std::end(data), std::ostream_iterator<int>(std::cout, ", "));
std::cout << "\n";
}