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;
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章