堆排序

算法的内容见算法导论堆排序章节

#include <iostream>
using namespace std;


struct Heap{
	int *data;
	int dateLength;//堆中的数据元素的个数
	int heapLength;//进行堆运算的元素的个数
};

int Parent(int i){//i节点对应的父节点
	return i/2;
}

int Left(int i){//i节点对应的左孩子
	return 2*i;
}

int Righ(int i){//i节点对应的右孩子
	return 2*i+1;
}



void InitHeap(int n,Heap *hp){//初始化一个含有n个元素的堆
	hp->data=new int[n+1];
	hp->dateLength=n;
	hp->heapLength=1;
	int i;
	for (i=1;i<=hp->dateLength;i++)
	{
		cin>>hp->data[i];
	}
}

void MaxHeapify(Heap *hp,int i){//对堆中的节点i进行 向下递归操作,维持堆的性质
	int l,r;
	l=Left(i);
	r=Righ(i);
	
	int largest;
	if (l<=hp->heapLength && hp->data[l]>hp->data[i] )
	{
		largest=l;
	}else{
		largest=i;
	}

	if (r<=hp->heapLength && hp->data[r]>hp->data[largest])
	{
		largest=r;
	}

	if (largest!=i)
	{
		int temp=hp->data[largest];
		hp->data[largest]=hp->data[i];
		hp->data[i]=temp;
		MaxHeapify(hp,largest);
	}
}


void BuildMaxHeap(Heap *hp){//建立一个大堆
	hp->heapLength=hp->dateLength;
	int i;
	for (i=hp->dateLength/2;i>=1;i--)
	{
		MaxHeapify(hp,i);
	}
}
void HeapShow(Heap *hp);//显示堆中的数据元素
void HeapSort(Heap *hp){//进行堆排序
	BuildMaxHeap(hp);
	HeapShow(hp);
	int temp;
	for (int i=hp->dateLength;i>=2;i--)
	{
		//swap
		temp=hp->data[hp->heapLength];
		hp->data[hp->heapLength]=hp->data[1];
		hp->data[1]=temp;

		hp->heapLength--;

		MaxHeapify(hp,1);
	}
}


int HeapMaxMum(Heap *hp){//返回大堆中的最大元素的值
	return hp->data[1];
}

int HeapExtractMax(Heap *hp){//移除堆中的最大元素
	int max=hp->data[1];
	hp->data[1]=hp->data[hp->heapLength];
	hp->heapLength--;
	MaxHeapify(hp,1);

	return max;
}

void HeapIncreaseKey(Heap *hp,int i,int key){//将大堆中的第i个元素的值增加到 key.并维持大堆性质
	if (key<hp->data[i])
	{
		return ;
	}

	hp->data[i]=key;

	int temp;
	while (i>1 && hp->data[Parent(i)]<hp->data[i])
	{
		//swap
		temp=hp->data[Parent(i)];
		hp->data[Parent(i)]=hp->data[i];
		hp->data[i]=temp;

		i=Parent(i);
	}
}

void MaxHeapInsert(Heap *hp,int key){//向大堆中添加值为key 的数据元素
	//
	if (hp->heapLength==hp->dateLength)
	{
		//overflow
		return ;
	}

	hp->heapLength++;
	hp->data[hp->heapLength]=0x8000;//the most min integer


	HeapIncreaseKey(hp,hp->heapLength,key);
}

void HeapShow(Heap *hp){
	int i;
	for (i=1;i<=hp->dateLength;i++)
	{
		cout<<hp->data[i]<<" ";
	}
	cout<<endl;
}

int main(int argc,char *argv[]){
	Heap *hp=new Heap;
	InitHeap(5,hp);

	BuildMaxHeap(hp);
	HeapShow(hp);
	HeapIncreaseKey(hp,3,6);
	
	HeapShow(hp);

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值