优先队列排序是堆的常见应用。优先队列和堆一样,有两种形式:最大优先队列和最小优先队列。
此处是基于最大堆实现最大优先队列。最大优先队列的应用有很多,其中一个就是在共享计算机系统的作业调度。
下面是代码:
"priorityQueue.h"
#include<stdio.h>
#include<limits.h>
#include<stdlib.h>
int heapMaximun(int *a);//返回队列中的最大值
int heapExtractMax(int *a,int n);//去掉并返回最大值
void heapIncreaseKey(int *a,int n,int i,int k);//将第i个数组元素的值提高到k
void maxHeapInsert(int *a,int n,int k);//把k插入到队列中
"priorityQueue.cpp"
#include"priorityQueue.h"
int parent(int i){
int j=i/2;
return j;
}
int left(int i){
return 2*i;
}
int right(int i){
return 2*i+1;
}
void maxHeapify(int *a,int n,int i){
int l,r,max,t;
l=left(i);
r=right(i);
if((l<=n)&&(a[l-1]>a[i-1]))
max=l;
else max=i;
if((r<=n)&&(a[r-1]>a[max-1]))
max=r;
if(max!=i){
t=a[i-1];
a[i-1]=a[max-1];
a[max-1]=t;
maxHeapify(a,n,max);
}
}
void buildMaxHeap(int *a,int n){
int i;
for(i=n/2;i>=0;i--){
maxHeapify(a,n,i+1);
}
for(i=0;i<n;i++){
printf("%d ",a[i]);
}
}
int heapMaximun(int *a,int n){
buildMaxHeap(a,n);
return a[0];
}
int heapExtractMax(int *a,int n){
buildMaxHeap(a,n);
printf("\n");
if(n<1){
printf("error:heap underflow");
return 0;
}
int max=a[0];
a[0]=a[n-1];
n=n-1;
maxHeapify(a,n,1);
for(int i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
return max;
}
void heapIncreaseKey(int *a,int n,int i,int k){
buildMaxHeap(a,n);
printf("\n");
if(k<a[i-1]){
printf("error:new key is smaller than current key.");
return ;
}
a[i-1]=k;
while((i-1>0)&&(a[parent(i)-1]<a[i-1])){
int t=a[i-1];
a[i-1]=a[parent(i)-1];
a[parent(i)-1]=t;
i=parent(i);
}
for(int i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
void maxHeapInsert(int *a,int n,int k){
buildMaxHeap(a,n);
printf("\n");
n=n+1;
a[n]=INT_MIN;
heapIncreaseKey(a,n,n,k);
for(int i=0;i<n;i++)
printf("%d ",a[i]);
}
"main.cpp"
#include"priorityQueue.h"
int main(){
int *a,*b,*c,n,i,x,k;
printf("Please input the number of array:\n");
scanf("%d",&n);
a=(int *)malloc(sizeof(int)*n);
b=(int *)malloc(sizeof(int)*n);
c=(int *)malloc(sizeof(int)*n);
printf("Plaease input the array:\n");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
b[i]=a[i];
c[i]=a[i];
}
int max=heapExtractMax(a,n);
printf("%d\n",max);
printf("Please input the number of increase element and the key:\n");
scanf("%d %d",&x,&k);
heapIncreaseKey(b,n,x,k);
printf("Please input the key to be inserted:\n");
scanf("%d",&k);
maxHeapInsert(c,n,k);
system("pause");
return 0;
}
这次实现的话,问题主要是我忘记要建堆了,就直接按照伪码来写,当然结果不对啦~
还有就是每次函数调用都要重新建堆,要不然上次函数调用就改变了数组的堆,结果当然也不对~