最大优先级队列(6)

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;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

byd yes

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值