大小根堆

大根堆、小根堆

定义结构体

typedef int DataType;
typedef struct StaticSequenceList{
    int size;
    int capacity;
    DataType *datas;
    int (*function)(int, int);
}Pile, *QPile;

创建大小根堆

int my_cmp_bigger(int a, int b)
{
    return a>b?1:0;
}

void PileInit(QPile pile)  //初始化
{
    assert(pile);
    pile->capacity = 0;
    pile->datas = NULL;
    pile->size = 0;
    pile->function = my_cmp_bigger;
}

static void PileEnlargeCapacity(QPile pile) //扩大堆的容量
{
   DataType *cache = NULL;
   assert(pile);
   cache = (DataType *)realloc(pile->datas, sizeof(DataType)*2*pile->capacity);
   if (cache != NULL)
   {
       pile->datas = cache;
       pile->capacity *=2;
   }   
   else
   {
       printf("错误,realloc失败,内存不足\n");
       exit(0);
   }
}

static void my_swap(int *a, int *b)
{
    int c = *a;
    *a = *b;
    *b = c;
}

static void AdjustPileDown(QPile pile, int parent)  //向下调整,用于对初始化的堆进行调整
{
/* 递归形式 */
    assert(pile);
    if (parent>=0 && parent<pile->size)
    {
        int child = parent*2+1;
        if ((child+1) < pile->size && (pile->function)(pile->datas[child+1], pile->datas[child]))
        {
            child++;
        }
        if (child < pile->size && (pile->function)(pile->datas[child], pile->datas[parent]))    
        {
            my_swap(&(pile->datas[parent]), &(pile->datas[child]));
        }

        AdjustPileDown(pile, child);
    }
/*  非递归形式
    int child = parent*2+1;
    assert(pile);
    while(child < pile->size)
    {
        if ((child+1) < pile->size && pile->datas[child] > pile->datas[child+1])
            child++;
         if (pile->datas[parent] > pile->datas[child])
         {
             my_swap(&(pile->datas[parent]), &(pile->datas[child]));
             parent = child;
             child = parent*2+1;
         }
         else
             return;
    }
*/
}

void PileCreat(QPile pile, DataType datas[], int len) //创建堆
{
    int LastParent = (len-2)/2;
    assert(pile);
    pile->datas = (DataType *)malloc(sizeof(DataType)*len); //为堆申请空间
    if (pile->datas != NULL)
    {
        int i;
        pile->size = len;
        pile->capacity = len;
        for (i = 0; i<len; i++)                  //复制初始数组中的元素到堆中
            pile->datas[i] = datas[i];
    }
    else
    {
        printf("错误,malloc失败,内存不足\n");
        exit(0);
    }
    for (LastParent; LastParent>=0; LastParent--)
    {
         AdjustPileDown(pile, LastParent);       //调整堆
    }

}


static void AdjustPileUp(QPile pile) //向上调整,用于对插入元素后的堆调整
{
    int child = pile->size-1;
    assert(pile);
    while((child-1)>=0 && (pile->function)(pile->datas[child], pile->datas[(child-1)/2]))
    {
        my_swap(&(pile->datas[child]), &(pile->datas[(child-1)/2]));
        child = (child-1)/2;
    }
}

猜你喜欢

转载自blog.csdn.net/neverwa/article/details/80311202