C#简单小顶堆的实现

using System;

/// <summary>
/// 小顶堆,T类型需要实现 IComparable 接口
/// </summary>
class MinHeap<T> where T : IComparable
{
    private T[] container; // 存放堆元素的容器
    private int capacity;  // 堆的容量,最大可以放多少个元素
    private int count; // 堆中已经存储的数据个数

    public MinHeap(int _capacity)
    {
        container = new T[_capacity + 1];
        capacity = _capacity;
        count = 0;
    }
    //插入一个元素
    public bool AddItem(T item)
    {
        if (count >= capacity)
        {
            return false;
        }
        ++count;
        container[count] = item;
        int i = count;
        while (i / 2 > 0 && container[i].CompareTo(container[i / 2]) < 0)
        {
            // 自下往上堆化,交换 i 和i/2 元素
            T temp = container[i];
            container[i] = container[i / 2];
            container[i / 2] = temp;
            i = i / 2;
        }
        return true;
    }
    //获取最小的元素
    public T GetMinItem()
    {
        if (count == 0)
        {
            return default(T);
        }
        T result = container[1];
        return result;
    }
    //删除最小的元素,即堆顶元素
    public bool DeteleMinItem()
    {
        if (count == 0)
        {
            return false;
        }
        container[1] = container[count];
        container[count] = default(T);
        --count;
        UpdateHeap(container, count, 1);
        return true;
    }
    //从某个节点开始从上向下 堆化
    private void UpdateHeap(T[] a, int n, int i)
    {
        while (true)
        {
            int maxPos = i;
            //遍历左右子树,确定那个是最小的元素
            if (i * 2 <= n && a[i].CompareTo(a[i * 2]) > 0)
            {
                maxPos = i * 2;
            }
            if (i * 2 + 1 <= n && a[maxPos].CompareTo(a[i * 2 + 1]) > 0)
            {
                maxPos = i * 2 + 1;
            }
            if (maxPos == i)
            {
                break;
            }
            T temp = container[i];
            container[i] = container[maxPos];
            container[maxPos] = temp;
            i = maxPos;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值