Priority Queues with C#: Listing 3.

Adding an item to a priority queue.

public void Enqueue(T item)
{
  data.Add(item);
  int ci = data.Count - 1;
  while (ci  > 0)
  {
    int pi = (ci - 1) / 2;
    if (data[ci].CompareTo(data[pi])  >= 0)
      break;
    T tmp = data[ci]; data[ci] = data[pi]; data[pi] = tmp;
    ci = pi;
  }
}

About the Author

Dr. James McCaffrey works for Microsoft Research in Redmond, WA. James has worked on several key Microsoft products such as Internet Explorer and Bing. James can be reached at jamccaff@microsoft.com.