/*
*利用最大堆实现一个最大优先队列
*/
#include <iostream>
using namespace std;
int *queue; //队列
int const maxLength = 5; //队列最大长度
int curLength = 0; //当前队列长度
void MAX_HEAPIFY(int*,int,int);
void MAX_HEAP_BUILD(int*,int length);
void SWAP(int*,int,int);
int GET_MAX(int*,int&);
void INSERT(int*,int,int);
void CHANGE_VALUE(int*,int,int);
void SWAP(int a[],int i,int j)
{
/*
*交换数组a中的a[i]和a[j]
*/
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
void MAX_HEAPIFY(int *s,int i,int length)
{
/*
*调整以i为根的树,使之为最大堆
*条件:i节点的左右子树均已经为最大堆
*length是当前队列长度
*数组的下标以0为开始
*/
int left = i*2+1;
int right = i*2+2;
int max = i; //记录根节点、左孩子、右孩子中最大值的那个编号
if(left<length && s[left]>s[max]) max = left;
if(right<length && s[right]>s[max]) max = right;
if(max != i)
{
SWAP(s,i,max);
MAX_HEAPIFY(s,max,length);
}
}
void MAX_HEAP_BUILD(int *s,int length)
{
/*
*将一个数组s构造成最大堆
*用于将一个非最大优先队列数组初始化为一个最大优先队列
*length是数组长度
*/
int n = (length-1)/2;
while(n >= 0)
{
MAX_HEAPIFY(s,n,length);
n--;
}
}
void CHANGE_VALUE(int *s,int i,int key)
{
/*
*将队列s中排在第i位的值改为key
*/
if(s[i]>key)
{
//新值没有改变最大优先队列性质
s[i] = key;
return;
}
else
{
s[i] = key;
int parent = (i-1)/2;
while(i>0 && s[parent]<s[i])
{
//将新值依次跟父节点比较,交换,直到找到合适的插入位置
SWAP(s,parent,i);
i = parent;
parent = (i-1)/2;
}
}
}
int GET_MAX(int *s,int &length)
{
if(length>0)
{
int max = s[0];
SWAP(s,0,length-1);
length--;
MAX_HEAPIFY(s,0,length);
return max;
}
else
{
cout<<"the queue is empty!"<<endl;
return 0;
}
}
void INSERT(int *s,int x,int &cur_length,int max_length)
{
/*
*将元素x插入到现有最大优先队列s中
*cur_length是现有队列的长度,max_length是最大长度
*/
if(cur_length < max_length)
{
cur_length++;
s[cur_length-1] =x;
CHANGE_VALUE(s,cur_length-1,x);
}
else
{
int max = GET_MAX(s,cur_length);
INSERT(s,x,cur_length,max_length);
cout<<"原队列已满,去取出原队列首元素:"<<max<<endl;
}
}
int main()
{
queue = new int[maxLength];
curLength = 0;
int n = 5;
int x;
while( n > 0 )
{
cout<<"insert num:";
cin>>x;
INSERT(queue,x,curLength,maxLength);
n--;
}
n = 5;
while(n >0)
{
cout<<"insert num:";
cin>>x;
INSERT(queue,x,curLength,maxLength);
n--;
}
n = 5;
while(n>0)
{
cout<<"依次输出队列中剩余元素:"<<endl;
cout<<GET_MAX(queue,curLength)<<endl;
n--;
}
}