當然,假設你使用一個數組類型來容納這個名單很容易。
我會假設Enemy
是您的班級名稱,並且該文件名爲Priority
以執行排序。我們需要一個IComparer<Enemy>
,看起來像下面這樣:
public class EnemyComparer : IComparer<Enemy>
{
int IComparer<Enemy>.Compare(Enemy x, Enemy y)
{
return y.Priority.CompareTo(x.Priority); // reverse operand to invert ordering
}
}
然後,我們可以如下編寫一個簡單的InsertEnemy
例行:
public static bool InsertEnemy(Enemy[] enemies, Enemy newEnemy)
{
// binary search in O(logN)
var ix = Array.BinarySearch(enemies, newEnemy, new EnemyComparer());
// If not found, the bit-wise compliment is the insertion index
if (ix < 0)
ix = ~ix;
// If the insertion index is after the list we bail out...
if (ix >= enemies.Length)
return false;// Insert is after last item...
//Move enemies down the list to make room for the insertion...
if (ix + 1 < enemies.Length)
Array.ConstrainedCopy(enemies, ix, enemies, ix + 1, enemies.Length - (ix + 1));
//Now insert the newEnemy into the position
enemies[ix] = newEnemy;
return true;
}
還有其他的數據結構,這將使這個有點快,但這應該證明是足夠有效的。如果列表變大,B樹或二叉樹就沒有問題,但對於10個項目來說,它可能會更快。
了與上述增加以下的測試方法:
public class Enemy
{
public int Priority;
}
public static void Main()
{
var rand = new Random();
// Start with a sorted list of 10
var enemies = Enumerable.Range(0, 10).Select(i => new Enemy() {Priority = rand.Next(0, 100)}).OrderBy(e => e.Priority).ToArray();
// Insert random entries
for (int i = 0; i < 100; i++)
InsertEnemy(enemies, new Enemy() {Priority = rand.Next(100)});
}
O(LOG 2(N)),即:儘量在中間插入 – xerx593
查找二進制搜索 – Alex