堆排序 大根堆

#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;
	}
} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值