二叉堆中的例程汇总

void Insert(int X, priorityQueue H)  
{  
    int i;  
  
    if(isFull(H))  
    {  
        printf("Priority queue is full");  
        return;  
    }  
    for(i = ++H->Size; H->Elements[i/2] > X; i /= 2)  
        H->Elements[i] = H->Elements[i/2];  
    H->Elements[i] = X;  
}  


int deleteMin(priorityQueue H)
{
    int i, Child;
    int minElement, lastElement;
    
    if(isEmpty(H))
    {
        printf("Priority queue is empty");
        return H->Elements[0];
    }
    minElement = H->Elements[1];
    lastElement = H->Elements[H->Size--];

    for(i = 1; i*2 <= H->Size; i = Child)
    {
        Child = i*2;
        if(Child != H->Size && H->Elements[Child+1] < H->Elements[Child])
            Child++;

    if(lastElement > H->Elements[Child])
        H->Elements[i] = H->Elements[Child];
    else
        break;
    }
    H->Elements[i] = lastElement;
    return minElement;
}


priorityQueue buildHeap(int a[], int n)
{
    int i, j;
    priorityQueue H;
    H = (priorityQueue)malloc(sizeof(priorityQueue));
    if(H == NULL)
        printf("Out of space!!!");
    H->Elements = (int *)malloc((n+1)*sizeof(int));
    if(H->Elements == NULL)
        printf("Out of space!!!");

    H->Capacity = n;
    H->Size = n;
    H->Elements[0] = -1;
    for(i=1; i<=n; i++)
	H->Elements[i] = a[i-1];

    for(j=n/2; j>0; j--)
	percolateDown(j, H);
	
    return H;
}


void percolateDown(int i, priorityQueue H)
{
    int j;	
    for(j=i; (2*j+1) <= H->Size && H->Elements[j]>Min(H->Elements[2*j],H->Elements[2*j+1]);)
    {
        if(H->Elements[2*j]<H->Elements[2*j+1])
        {
            Swap(&H->Elements[j], &H->Elements[2*j]);
            j *= 2;
        }
        else
        {
            Swap(&H->Elements[j], &H->Elements[2*j+1]);
            j = 2*j+1;
        }
    }            
}

//二叉堆的上滤例程
void percolateUp(int i, priorityQueue H)
{
    int j;
    for(j = i; j/2 > 0 && H->Elements[j] < H->Elements[j/2]; j /= 2)
        Swap(&H->Elements[j], &H->Element[j/2]);
}

int findMin(priorityQueue H)
{
    if(isEmpty(H))
    {
        printf("Priority queue is empty");
        return H->Elements[0];
    }
    
    return H->Elements[1];
}


//降低或增加关键字的值
priorityQueue decreaseKey(int P, int Delta, priorityQueue H)
{
    H->Elements[P] -= Delta;
    percolateUp(P, H);

    return H;
}
priorityQueue increaseKey(int P, int Delta, priorityQueue H)
{
    H->Elements[P] += Delta;
    percolateDowm(P, H);

    return H;
}

priorityQueue Delete (int P, priorityQueue H)
{
    decreaseKey(P, INT_MAX, H);
    deleteMin(H);

    return H;
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值