Skip to content

Instantly share code, notes, and snippets.

@jmkim
Created June 9, 2016 13:22
Show Gist options
  • Save jmkim/1920a4ff2ac3cb0252d6a76f3c8d97cc to your computer and use it in GitHub Desktop.
Save jmkim/1920a4ff2ac3cb0252d6a76f3c8d97cc to your computer and use it in GitHub Desktop.
Concept of heapify in C++
#ifndef ALGORITHM_HEAP_H_
#define ALGORITHM_HEAP_H_ 1
#include <functional>
#include <utility>
#include <vector>
#include <iostream>
namespace algorithm
{
template<
typename ElementType,
typename ElementCompareFunc = std::less<ElementType>,
typename HeapType = std::vector<ElementType>
>
class Heap : public HeapType
{
private:
typedef int KeyType;
inline
KeyType
parent(const KeyType & me)
const
{ return ((me - 1) / 2); }
inline
KeyType
left(const KeyType & me)
const
{ return (2 * me + 1); }
inline
KeyType
right(const KeyType & me)
const
{ return (2 * me + 2); }
public:
void
Heapify(void)
{
for(int pos = this->size() - 1; pos >= 0; --pos)
{
KeyType start = this->parent(pos);
KeyType end = pos;
if(ElementCompareFunc()(this->at(start), this->at(pos)))
continue;
printf("START: %d (POS: %d)\n", start, pos);
printf(" LEFT: %d\n"
" RIGHT: %d\n", left(pos), right(pos));
//while(left(last) < this->size() && ElementCompareFunc()(this->at(last = (ElementCompareFunc()(this->at(left(last)), this->at(right(last))) ? left(last) : right(last))), this->at(pos)))
while(right(end) < this->size())
{
KeyType temp = (ElementCompareFunc()(this->at(left(end)), this->at(right(end))) ? left(end) : right(end));
if(ElementCompareFunc()(this->at(temp), this->at(pos)))
break;
end = temp;
printf("END: %d\n", end);
}
printf("END: %d (POS: %d)\n", end, pos);
if(end == pos)
std::swap(this->at(start), this->at(pos));
else
{
KeyType cpos = end; /** Child position */
do
{
cpos = parent(pos);
std::swap(this->at(end), this->at(cpos));
}
while(cpos != parent(pos));
}
for(int i = 0; i < this->size(); ++i)
printf("%3d ", this->at(i));
std::cout << std::endl;
}
}
};
}
using namespace algorithm;
int main(void)
{
int arr[] = { 7, 5, 13, 0, 1, 7, 6, 4, 3, 2 };
Heap<int> heap;
heap.insert(heap.begin(), arr, arr + 10);
heap.Heapify();
for(auto node : heap)
printf("%3d ", node);
std::cout << std::endl;
return 0;
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment