c++&&堆

#include<iostream>
#include<string>
#include<vector>
#include<string.h>
#include<Windows.h>
using namespace std;
class heap
{ private:
	   int *v;
	   int heap_size;
  public:
	 heap() {}
	 heap(int size)
	 {  heap_size=size;
	    v=new int[10*size] ;
		v[0]=0;//标志位
		cout<<"please input Array element:"<<endl;
		for(int i=1;i<=size;++i)
			cin>>v[i];
	 }
	 void build_max_heap();//创建最大堆
	 void max_heapify(int i);//保持最大堆的性质
	 void heapsort();//堆排序
	 int  heap_maxnum();//返回堆中最大值
	 int  heap_extramax();//返回堆的最大值并删除
	 void heap_increase_key(int i,int key);//修改堆中i位置的元素的值
	 void max_heap_insert(int key);//在堆中插入一个元素
	 void output();//输出堆中的元素
	 ~heap()
	 {delete []v;}
};
void heap::max_heapify(int i)
{   int n=heap::heap_size;
    int l=i<<1,r=(i<<1)+1,largest=i;
	if(l<=n&&v[l]>v[largest]) largest=l;
	if(r<=n&&v[r]>v[largest])  largest=r;
	if(largest!=i)
	 {int temp=v[i];
	   v[i]=v[largest];
	   v[largest]=temp;
	   max_heapify(largest);
	 }
 }
void heap::build_max_heap()
{   int n=heap::heap_size;
    for(int i=n/2;i>0;--i)
	   max_heapify(i);
}
void heap::heapsort()
{    build_max_heap();
	int n=heap::heap_size;
    for(int i=n;i>1;--i)
	{ int temp=v[i];
	    v[i]=v[1];
		v[1]=temp;
		heap::heap_size--;
		max_heapify(1);
	}
	 for(int i=0;i<=n;++i)
	  cout<<v[i]<<" ";
      cout<<endl;
}
int  heap::heap_maxnum()
{  build_max_heap();
   return v[1];
 }
int heap::heap_extramax()
{    int n=heap::heap_size;
	int max=v[1];
      v[1]=v[n];
	heap::heap_size--;
	max_heapify(1);
	return max;
}
void heap::heap_increase_key(int i,int key)
{   if(v[i]>key)
       { v[i]=key;
         max_heapify(i);
       }
    else {
		   v[i]=key;
		    while(i>1&&v[i/2]<v[i])
			{ int temp=v[i];
			  v[i]=v[i/2];
			  v[i/2]=temp;
			  i=i/2;
			}
         }
}
void heap::max_heap_insert(int key)
{   
        heap::heap_size++;
		int n=heap::heap_size;
		v[n]=-0xffff;
		heap_increase_key(n,key);
}
void heap::output()
{ int n=heap::heap_size;
  for(int i=0;i<=n;++i)
	  cout<<v[i]<<" ";
      cout<<endl;
	  
}
int main()
{  system("color 1C");
  heap s(10);
  cout<<"bulit_maxheap:"<<endl;
  s.build_max_heap();
  cout<<"output the heap: ";
  s.output();
  cout<<"please output the heap maxnum: ";
  cout<<s.heap_maxnum()<<endl;
  cout<<"please output the heap maxum and delete it: ";
  cout<<s.heap_extramax()<<endl;
  cout<<"output the heap: ";
  s.output();
  cout<<"please input a key to insert the heap : ";
  int key;
  cin>>key;
  s.max_heap_insert(key);
  cout<<"output the heap: ";
  s.output();
  cout<<"plese input a position and a key : ";
  int i;
  cin>>i>>key;
  s.heap_increase_key(i,key);
  cout<<"output the heap: ";
  s.output();
  cout<<"the heap after sort:";
  s.heapsort();
  return 0;
 }

输出结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值