堆排序的实现

堆排序c++实现

//大堆比较
template<class T>
bool max_compare(T a, T b)
{
    return a < b;
}
//小堆比较
template<class T>
bool min_compare(T a, T b)
{
    return a > b;
}
template<class T>
void heapify(T *src, int start,int len,bool (*compare)(T ,T ))
{
    int left = (start + 1)*2 - 1;
    int right = left + 1;
    int temp = start;
    while (true)
    {
        if (left<len && compare(src[temp] , src[left]))
            temp = left;
        if (right<len && compare(src[temp] , src[right]))
            temp = right;
        if (start == temp)
            break;
        swap(src[start], src[temp]);
        start = temp;
        left = (start+1)*2  - 1;
        right = left + 1;
    }
}
template<class T>
void build_heap(T* src, int len, bool(*compare)(T, T))
{
    int i;
    for (i = (len/2)-1; i >= 0; i--)
        heapify(src, i, len, compare);
}
template<class T>
void sort_head(T* src, int len, bool(*compare)(T, T))
{
    assert(len > 0);
    build_heap(src, len, compare);
    while (len > 0)
    {
        swap(src[0], src[--len]);
        heapify(src, 0, len, compare);
    }
}
void test_heap()
{
    
    int a[] = { 5, 4, 8, 2, 1, 12 };
    sort_head(a, 6, min_compare);
    for (int i = 0; i < 6; i++)
        cout << a[i] << ",";
    cout << endl;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值