#include <iostream>
#include <algorithm>
using namespace std;
#define MAX 100010
int Heap[MAX];
//Heap[i]的孩子是 2*i+1 2*i+2 父亲是(i-1)/2
int HeapSize = 0;//初始化堆的大小
void HeapInsert(int Index);//对Index位置上的数进行插入
void Heapify(int Index);
int main(int argc, char** argv)
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
scanf("%d", &Heap[i]);
}
//对0 - n-1的数 进行堆插入操作
for(int i = 0; i < n; i++)
{
HeapInsert(HeapSize);
HeapSize++;
}
for(int i = 0; i < n; i++)
{
Heapify(HeapSize);
}
return 0;
}
void HeapInsert(int Index)
{
int Father = (Index-1)/2;
//当这个节点 比 他的父亲节点 大的时候
while(Heap[Index] > Heap[Father] )
{
swap(Heap[Index], Heap[Father]);
Index = Father;
Father = (Father-1)/2;
}
}
void Heapify(int Index)
{
printf("%d ",Heap[0]);
swap(Heap[0],Heap[Index]);
HeapSize--;
Index = 0;
while(Index <= HeapSize)
{
int Left = Index*2+1; int Right = Index*2+2;
//没有孩子 不用交换
if(Left > HeapSize)
{
break;
}
//选出左右孩子的最大位置 注意 左右孩子没有的情况
int MaxPos = (Right <= HeapSize)&&(Heap[Right]>Heap[Left])
? Right : Left;
MaxPos = Heap[Index] > Heap[MaxPos] ? Index : MaxPos;
if(MaxPos == Index)
{
break;
}
swap(Heap[Index],Heap[MaxPos]);
Index = MaxPos;
}
}
堆排序 大根堆
最新推荐文章于 2024-07-23 22:06:37 发布