1.理论参见:http://www.cnblogs.com/Anker/archive/2013/01/23/2873951.html
2.c代码
/*************************************************************************
> File Name: maxPriorityQueue.c
> Author: NULL
> Mail: 574889524@qq.com
> Created Time: Tue 14 Oct 2014 07:48:57 PM CST
************************************************************************/
#include<stdio.h>
#define ARRSIZE 10
/****************************************/
void ExChangeInt(int *a,int *b)
{
int iTemp = *a;
*a = *b;
*b = iTemp;
}
void PrintArrInt(int *a,int iLarg)
{
int i;
for(i = 0;i < iLarg;++i)
printf("%d ",a[i]);
printf("\n");
}
int Parent(int i)
{
return (i-1)/2;
}
int Leaf(int i)
{
return 2*i+1;
}
int Right(int i)
{
return 2*i+2;
}
/************************************************/
static int giHeapSize = ARRSIZE - 1;;
void MaxHeapIfy(int *A,int i)
{
int iLargest;
int iL = Leaf(i);
int iR = Right(i);
if((iL<=giHeapSize) && (A[iL] > A[i]))
iLargest = iL;
else
iLargest = i;
if((iR <=giHeapSize) && (A[iR] > A[iLargest]))
iLargest = iR;
if(iLargest != i){
ExChangeInt(&A[i],&A[iLargest]);
MaxHeapIfy(A,iLargest);
}
}
void BuilMaxHeap(int *A)
{
int i;
for(i = (ARRSIZE-1)/2;i>=0;--i)
MaxHeapIfy(A,i);
}
int HeapExtractMax(int *A)
{
int iMax;
if(giHeapSize < 0){
printf("heap underflow");
return -1;
}
iMax = A[0];
A[0] = A[giHeapSize];
giHeapSize--;
MaxHeapIfy(A,0);
return iMax;
}
int HeapMaxNum(int *A)
{
return A[0];
}
void HeapIncreaseKey(int *A,int i,int key)
{
if(0 == i)
return;
if(key < A[i]){
printf("new key is samaller than key");
return;
}
A[i] = key;
while((i > 0) && (A[Parent(i)] < A[i])){
ExChangeInt(&A[i],&A[Parent(i)]);
i = Parent(i);
}
}
void MaxHeapInsert(int *A,int key)
{
giHeapSize++;
A[giHeapSize] = -10000;
HeapIncreaseKey(A,giHeapSize,key);
}
/***********************************************************************************/
int main()
{
int A[ARRSIZE] = {4,1,3,2,16,9,10,14,8,7};
int i,k ;
BuilMaxHeap(A);
i= HeapExtractMax(A);
printf("i = %d\n",i);
MaxHeapInsert(A,90);
i= HeapExtractMax(A);
printf("i = %d\n",i);
return 0;
}