private void SiftDown(int index) { PriorityQueueNodeWrapper min = minHeap[index]; int minIndex = index; int leftChildIndex = GetLeftChildIndex(index); if (leftChildIndex < Count() && ComparePriorities(minHeap[leftChildIndex], min) < 0) { min = minHeap[leftChildIndex]; minIndex = leftChildIndex; } int rightChildIndex = GetRightChildIndex(index); if (rightChildIndex < Count() && ComparePriorities(minHeap[rightChildIndex], min) < 0) { minIndex = rightChildIndex; } if (minIndex != index) { SwapAndUpdateMap(index, minIndex); SiftDown(minIndex); } }
private void AttachNodeAtIndex(PriorityQueueNodeWrapper wrapper, int index) { GrowHeapByOne(); this.minHeap[index] = wrapper; this.nodeUniqueKeyToHeapIndexMap[wrapper.Data.UniqueKey] = index; }
public void Enqueue(PriorityQueueNode node) { int lastIndex = Count(); PriorityQueueNodeWrapper wrapper = new PriorityQueueNodeWrapper(node); AttachNodeAtIndex(wrapper, lastIndex); SiftUp(lastIndex); }
private PriorityQueueNodeWrapper DetachNodeAtIndex(int index) { PriorityQueueNodeWrapper wrapper = minHeap[index]; this.nodeUniqueKeyToHeapIndexMap.Remove(wrapper.Data.UniqueKey); ShrinkHeapByOne(); return(wrapper); }
private int ComparePriorities(PriorityQueueNodeWrapper node1, PriorityQueueNodeWrapper node2) { int result = node1.Priority.CompareTo(node2.Priority); if (result == 0) { result = node1.Sequence.CompareTo(node2.Sequence); } return(result); }
public override string ToString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < heapCount; i++) { PriorityQueueNodeWrapper wrapper = minHeap[i]; sb.AppendLine(string.Format("HeapIndex: {0} UniqueKey: {1} Priority: {2} Sequence: {3}", i, wrapper.Data.UniqueKey, wrapper.Priority, wrapper.Sequence)); } return(sb.ToString()); }
public PriorityQueueNode Dequeue() { if (minHeap.Count == 0) { throw new PriorityQueueEmptyException(); } int topIndex = 0; PriorityQueueNodeWrapper min = DetachNodeAtIndex(topIndex); int lastIndex = Count(); PriorityQueueNodeWrapper last = DetachNodeAtIndex(lastIndex); AttachNodeAtIndex(last, topIndex); SiftDown(0); return(min); }