堆排序(大顶堆)

# ifndef maxheap
# define maxheap
# include<iostream>
using namespace std;
const int capacity=100;
class maxHeap
{
	public:
      maxHeap()
	  {
	  	heap=new int [capacity];
	  	heapsize=0;
	  	arraylength=capacity;
	  }	
	 void push(const int &data);
	 void initialize(int a[],int thesize);
	 void pop();
	 int top()
	 {
	 	return heap[1];
	 }
	protected:
		int *heap;
	   int arraylength;
	   int heapsize;
};

	
void maxHeap::initialize(int a[],int thesize)
{
	heapsize=thesize;    //规模初始化
	  for(int i=0;i<thesize;i++)
	     heap[i+1]=a[i];      //赋值 ,注意heap[0]不使用
	for(int root=heapsize/2;root>=1;root--)
	{
		int thedata=heap[root];
		int child=root*2;
		while(child<=heapsize)  //循环结束条件:child>heapsize||thedata>heap[child];
		{
			if(child<heapsize&&heap[child]<heap[child+1])
			  child++;     //选取最大孩子进行比较,依据:大于最大的数,就大于任何一个数。
			if(thedata>heap[child])    //如果此数比最大的孩子节点的值大,就结束while循环,执行循环外的赋值语句。
			  break;  
			if(thedata<=heap[child])   //如果此数比最大的孩子节点的值小,就将最大孩子的值赋给父节点,即孩子的值上移,孩子节点移到下一层
			 {
			 	heap[child/2]=heap[child];
			 	child*=2;
			 	
			 }
		}
		
		heap[child/2]=thedata;
	}
	
}

void maxHeap::push(const int &data)
{
 int currnode=++heapsize;//选新增节点为当前节点
 int i;
 	for(i=currnode/2;i>=1;i/=2)     //i表示currnode的父节点。
 	{
 		if(data<=heap[i])     //如果data的值比父节点的值小,那么终止循环。
 		  break;
 		if(data>heap[i])     ///如果data的值比父节点的值大,父节点的值下移。
 		{
 			currnode=i;
 			heap[i*2]=heap[i];	
		 }
	 }
	 heap[currnode]=data;   //循环终止后执行赋值。
}
//删除堆顶元素,使用最后一个元素重构大顶堆 。
void maxHeap::pop()  
{
	int lastdata=heap[heapsize--];   //
	int root=1;
	int child=root*2;
	while(child<=heapsize)
	{
		
		if(child<heapsize&&heap[child]<heap[child+1])  //选取最大孩子进行比较,依据:大于最大的数,就大于任何一个数。
		   child+=1;
		if(lastdata>heap[child])  如果此数比最大的孩子节点的值大,就结束while循环,执行循环外的赋值语句
		    break;    
		if(lastdata<heap[child])  //如果此数比最大的孩子节点的值小,就将最大孩子的值赋给父节点,即孩子的值上移,孩子节点移到下一层
		  {
		  	heap[root]=heap[child];
		  	root=child;
		  	child*=2;   //孩子节点移到下一层
		  }
	}
	
	heap[root]=lastdata;
}
# endif
# include<iostream>
# include"maxheap.cpp"
using namespace std;
int main()
{
	maxHeap s;
	int n;
	cin>>n;
	int a[n];
	for(int i=0;i<n;i++)
	  cin>>a[i];
	s.initialize(a,n);
	for(int i=0;i<n;i++)
	{
	   a[i]=s.top();
	   s.pop();  	
	  }
	  for(int i=0;i<n;i++)
	    cout<<a[i]<<" ";
	    cout<<endl;
	return 0;
}

学了堆排序的思想就可以直接对数组使用类似堆排序的算法进行排序。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值