c#的优先队列实现

如果不考虑顺序问题,可以使用那个折半插入,来减少插入排序的时间复杂度

using System;
using System.Collections;
using System.Collections.Generic;
public class PriorityQueue<T, P> where P : IComparable<P>
{
    private List<KeyValuePair<T, P>> items = new List<KeyValuePair<T, P>>();
    public int Count { get { return items.Count; } }
    public void Clear() { items.Clear(); }
    public void Enqueue(T item, P priority)
    {
        //从队尾开始,顺序查找插入
        int i = items.Count - 1;
        while (i >= 0)
        {
            int result = items[i].Value.CompareTo(priority);
            if (result > 0)
                i--;
            else
            {
                break;
            }
        }
        items.Insert(i + 1, new KeyValuePair<T, P>(item, priority));
        //折半插入
        //int i = 0, j = items.Count - 1;
        //while (i <= j)
        //{
        //    int middle = (i + j) / 2;
        //    int result = items[middle].Value.CompareTo(priority);
        //    if (result > 0)
        //    {
        //        j = middle - 1;
        //    }
        //    else if (result < 0)
        //    {
        //        i = middle + 1;
        //    }
        //    else
        //    {
        //        i = middle;
        //        break;
        //    }
        //}
        //items.Insert(i, new KeyValuePair<T, P>(item, priority));
    }
    public T Dequeue()
    {
        T first = items[0].Key;
        items.RemoveAt(0);
        return first;
    }
}
最近的文章

Unity3D屏幕震动脚本,集合了曲线功能

震屏功能的主代码,挂在MainCamera上比较好{% highlight c %}using System.Collections;using System.Collections.Generic;using UnityEngine;/// <summary>/// 震屏功能/// </summary>// [SLua.CustomLuaClass]public class ShakeCamera : MonoBehaviour{ /// <summa...…

继续阅读
更早的文章

UnityEditor扩展:自定义Hierarchy图标

能上代码就不BB了。参考自:http://answers.unity3d.com/questions/431952/how-to-show-an-icon-in-hierarchy-view.htmlusing UnityEditor;using UnityEngine;using System.Collections.Generic;[InitializeOnLoad]class HierarchyIconDisplay{ static Texture2D texture; ...…

继续阅读