#ifndef HEAP_SORT #define HEAP_SORT #include #include int Parent(int i) { return (i-1)/2;} int LeftChild(int i) {return 2*i+1;} int RightChild(int i) {return 2*i + 2;} template void HeapifyUp(std::vector & data, int pos){ int parentPos; while (pos > 0) { parentPos = Parent(pos); if (data[pos] > data[parentPos]) { std::swap(data[pos], data[parentPos]); pos = parentPos; } else { pos = 0; } } } template void HeapifyDown(std::vector & data, int pos, int size){ int left{LeftChild(pos)}, right{RightChild(pos)}, tmp{left}; while (left <= size) { if (right <= size and data[left] < data[right]) { tmp = right; } if (data[tmp] > data[pos]) { std::swap(data[pos], data[tmp]); pos = tmp; } else { pos = size; } tmp = left = LeftChild(pos); right = RightChild(pos); } } template void HeapSort(std::vector & data) { int i{0}; int size{static_cast(data.size())-1}; for(i = 1 ; i < static_cast(data.size()); i++) { HeapifyUp(data, i); } while (size > 0) { std::swap(data[0], data[size]); size --; HeapifyDown(data, 0, size); } } #endif