private PriorityQueueItem <TValue, TPriority> RemoveAt(Int32 index) { PriorityQueueItem <TValue, TPriority> o = items[index]; --numItems; // move the last item to fill the hole PriorityQueueItem <TValue, TPriority> tmp = items[numItems]; // If you forget to clear this, you have a potential memory leak. items[numItems] = default(PriorityQueueItem <TValue, TPriority>); if (numItems > 0 && index != numItems) { // If the new item is greater than its parent, bubble up. int i = index; int parent = (i - 1) / 2; while (compareFunc(tmp.Priority, items[parent].Priority) > 0) { items[i] = items[parent]; i = parent; parent = (i - 1) / 2; } // if i == index, then we didn't move the item up if (i == index) { // bubble down ... while (i < (numItems) / 2) { int j = (2 * i) + 1; if ((j < numItems - 1) && (compareFunc(items[j].Priority, items[j + 1].Priority) < 0)) { ++j; } if (compareFunc(items[j].Priority, tmp.Priority) <= 0) { break; } items[i] = items[j]; i = j; } } // Be sure to store the item in its place. items[i] = tmp; } //if (!VerifyQueue()) //{ // Console.WriteLine("ERROR: Queue out of order!"); //} return(o); }
public void Enqueue(PriorityQueueItem <TValue, TPriority> newItem) { if (numItems == capacity) { // need to increase capacity // grow by 50 percent SetCapacity((3 * Capacity) / 2); } int i = numItems; ++numItems; while ((i > 0) && (compareFunc(items[(i - 1) / 2].Priority, newItem.Priority) < 0)) { items[i] = items[(i - 1) / 2]; i = (i - 1) / 2; } items[i] = newItem; //if (!VerifyQueue()) //{ // Console.WriteLine("ERROR: Queue out of order!"); //} }