private void SortDown(HeapNode <T> item) { while (true) { int childIndexLeft = item.HeapIndex * 2 + 1; int childIndexRight = item.HeapIndex * 2 + 2; int swapIndex = 0; if (childIndexLeft < currentItemCount) { swapIndex = childIndexLeft; if (childIndexRight < currentItemCount && items[childIndexLeft].Node.CompareTo(items[childIndexRight].Node) < 0) { swapIndex = childIndexRight; } if (item.Node.CompareTo(items[swapIndex].Node) < 0) { Swap(item, items[swapIndex]); } else { return; } } else { return; } } }
private void Swap(HeapNode <T> itemA, HeapNode <T> itemB) { items[itemA.HeapIndex] = itemB; items[itemB.HeapIndex] = itemA; int itemAIndex = itemA.HeapIndex; itemA.HeapIndex = itemB.HeapIndex; itemB.HeapIndex = itemAIndex; }
public void Push(T item) { HeapNode <T> newNode = new HeapNode <T>(item); newNode.HeapIndex = currentItemCount; items[currentItemCount] = newNode; SortUp(newNode); ++currentItemCount; }
private void SortUp(HeapNode <T> item) { int parentIndex = (item.HeapIndex - 1) / 2; while (true) { HeapNode <T> parentItem = items[parentIndex]; if (item.Node.CompareTo(parentItem.Node) > 0) { Swap(item, parentItem); } else { break; } parentIndex = (item.HeapIndex - 1) / 2; } }