struct HEAP
{
vector<int> arr;
int sizeHeap;
explicit HEAP(const vector<int> &src)
{
sizeHeap = src.size();
arr = src;
buildMaxHeap();
}
// Get the left child index
inline int Left(int i)
{
return (i << 1) + 1;
}
// Get the right child index
inline int Right(int i)
{
return (i << 1) + 2;
}
// Max heap
void maxHeapify(int index)
{
int l = Left(index);
int r = Right(index);
int largest = -1;
if(l < sizeHeap and arr[l] > arr[index])
largest = l;
else
largest = index;
if(r < sizeHeap and arr[r] > arr[largest])
largest = r;
if(largest not_eq index)
{
std::swap(arr[index], arr[largest]);
maxHeapify(largest);
}
}
// Build a max heap
void buildMaxHeap()
{
for(int i = (arr.size() - 1) / 2; i >= 0; --i)
{
maxHeapify(i);
}
}
// Heap sort
vector<int> heapSort()
{
for(int i = arr.size() - 1; i >= 1; --i)
{
std::swap(arr[0], arr[i]);
--sizeHeap;
maxHeapify(0);
}
return arr;
}
};HeapSort -- 堆排序
最新推荐文章于 2023-05-13 14:02:01 发布
本文介绍了一种基于最大堆的数据结构实现,并详细解释了如何通过该数据结构进行堆排序的过程。文中提供了一个具体的C++代码示例,包括构建最大堆、获取子节点索引、维护最大堆性质的方法及堆排序算法。
229

被折叠的 条评论
为什么被折叠?



