堆排序总结

对于使用堆,其实质上是对完全二叉树进行操作,在理论上看成是树形结构,但在实际代码中,使用数组在进行相关的操作。由于堆会有动态增加元素的功能,所以最好使用容器,不要使用数组,现将以前代码都换成容器,但切记,一定要引用,因为如果是数组,传递给函数的是数组指针,可以直接修改值,而容器是对象,不能直接修改,所以要用引用。
其所有函数的相关代码如下:

//建堆
void Insert::BuileMaxHeap(vector<int> &A,int total)
{
    int roots=total/2-1;//建堆时,把数组元素后一半的视为完全二叉树即堆的叶子.
    for(;roots>=0;--roots)
    {
        MaxHeapIFY(A,roots,total);
    }

}
void Insert::MaxHeapIFY(vector<int> &A,int local,int total)//堆维护,最重要
{
    int left_child=(local+1)*2-1;//因为是从0开始计数,所以计算公式有2i变为此公式
    int right_child=(local+1)*2;
    int largest=local;
    if(left_child<total && A[local] < A[left_child])
    {
        largest=left_child;
    }   
    if(right_child<total && A[largest] < A[right_child])
    {
        largest=right_child;
    }
    if(largest!=local)
    {
        int temp=A[local];
        A[local]=A[largest];
        A[largest]=temp;
        MaxHeapIFY(A,largest,total);
    }
}

void Insert::HeapSort(vector<int> &A,int total)//堆排序从小到大
{
    int temp=0;
    for(int i=total-1;i>=1;--i)
    {
        temp=A[i];
        A[i]=A[0];
        A[0]=temp;
        --total;
        MaxHeapIFY(A,0,total);

    }

}

//一下是最大优先队列的函数,针对于堆
int Insert::MaxKeyValue(vector<int> &A)//对于堆而言
{
    return A[0];
}

void Insert:: HeapIncreseKey(vector<int> &A,int value,int key)
{
   if(key<A[value])
   {
       cout<<"this key is lower than themself!";
       return;
   }
   A[value]=key;
   while(value>0 && A[value/2] < A[value])//父节点<子节点
   {
        int temp=0;
        temp=A[value/2];
        A[value/2]=A[value];
        A[value]=temp;  
        value/=2;//value始终位子节点
   }       
}

void Insert::MaxHeapInsert(vector<int> &coll,int key)
{
    coll.push_back(-65535);
    int temp=coll.size();
    HeapIncreseKey(coll,temp-1,key);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值