堆的一些简单操作

  仅仅是记录一下自己写过的堆操作的代码,个人觉得堆的优势在于建立和获取最小或者最大元的方便,有任何次序要求的算法,堆并不合适。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _priorityqueue
{
    int capacity;
    int currentsize;
    int *member;

}priorityqueue;

void printpriorityqueue(priorityqueue *pq)
{
    for(int i = 1;i<pq->currentsize+1;i++)
        printf("%d\t",pq->member[i]);
    printf("\n");
    printf("\n");
    return;
}
priorityqueue* percolateup(priorityqueue *pq,int i)
{
    int tmp = pq->member[i];
    if(pq == 0)
        return 0;

    for(;pq->member[i/2] > tmp;i=i/2)
        pq->member[i] = pq->member[i/2];
    pq->member[i] = tmp;
    return pq;
}

priorityqueue* percolatedown(priorityqueue* pq,int i)
{
    int tmp = pq->member[i];
    if(pq == 0)
        return 0;
    if(pq->currentsize%2 == 0 && pq->currentsize < pq->capacity)
        pq->member[pq->currentsize + 1] = 0xffffff;
    for(;2*i<pq->currentsize+1;)
    {
        i = pq->member[2*i] < pq->member[2*i+1]?2*i:2*i+1;
        if (pq->member[i] < tmp)
        {
            //tmp = pq->member[i/2];
            pq->member[i/2] = pq->member[i];
            //pq->member[i] = tmp;
        }
        else{
            //pq->member[i/2] = tmp;
            i = i/2;
            break;
        }
    }
    pq->member[i] = tmp;
    return pq;
}

priorityqueue* initialize(int capacity,int current,int *a)
{
    int i;
    priorityqueue *tmp = (priorityqueue *)malloc(sizeof(priorityqueue));
    if(tmp == 0)
        return 0;
    tmp->capacity = capacity;
    tmp->currentsize = current;
    tmp->member = (int *)malloc(sizeof(int)*(capacity+1));
    if (tmp->member == 0)
    {
        free(tmp);
        return 0;
    }
    memset(tmp->member,0,sizeof(int)*(capacity+1));
    tmp->member[0] = -1;
    for(i=1;i<current+1;i++)
        tmp->member[i] = a[i-1];
    for(i = tmp->currentsize/2;i>0;i--){
        tmp = percolatedown(tmp,i);
        printpriorityqueue(tmp);
    }
    return  tmp;
}

priorityqueue *insert(priorityqueue *pq,int m)
{
    int i;
    if(pq == 0)
        return 0;
    if(pq->currentsize == pq->capacity)
        return 0;
    for(i = pq->currentsize;pq->member[i/2] > m;i = i/2)
        pq->member[i] = pq->member[i/2];
    pq->member[i] = m;
}

int deletemin(priorityqueue *pq)
{
    int tmp = pq->member[1];
    pq->currentsize--;
    if(pq->currentsize == 0)
        return tmp;
    pq->member[1] = pq->member[pq->currentsize + 1];
    percolatedown(pq,1);
    return tmp;
}


int findmin(priorityqueue *pq)
{
    return pq->member[1];
}

int main()
{
    int a[] = {150,80,40,30,10,70,110,100,20,90,60,50,120,140,130};
    priorityqueue *pq = initialize(31,15,a);
    for(int i  = 0;i<15;i++)
        printf("%d\t",deletemin(pq));
    while(1);
}

 

posted @ 2016-07-20 15:49  __sipl  阅读(203)  评论(0编辑  收藏  举报