I'm trying to implement Heap into my A* algorithm, However I'm having trouble with implementing one method. The Contains method. Which checks if the heap array has a specific node in it or not. I don't know how to implement that. If I just make a for loop and check every item in the heap that would be very very slow and defeat the purpose of a heap.
So my question is, How do you check if an item exist in a OpenSet of type Heap? What is the fastest way to do it?
This is my heap code:
namespace AI
{
public interface IHeapItem<T> : IComparable<T>
{
int HeapIndex { get; set; }
}
class Heap<T> where T : IHeapItem<T>
{
T[] Items;
int count;
public int Count { get { return count; } }
public Heap(int MaxSize)
{
Items = new T[MaxSize];
}
public T this[int Index]
{
get
{
if (Index > count)
Index = count - 1;
return Items[Index];
}
set { Items[Index] = value; }
}
public void Push(T Item)
{
Item.HeapIndex = count;
Items[count] = Item;
SortUp(Item);
count++;
}
public T Pop()
{
T FirstItem = Items[0];
count--;
Items[0] = Items[count];
Items[0].HeapIndex = 0;
SortDown(Items[0]);
return FirstItem;
}
public bool Contains(T Item)
{
}
void SortDown(T Item)
{
while (true)
{
int LeftChildIndex = Item.HeapIndex * 2 + 1;
int RightChildIndex = Item.HeapIndex * 2 + 2;
int swapIndex = 0;
if (LeftChildIndex < count)
{
swapIndex = LeftChildIndex;
if (RightChildIndex < count)
if (Items[LeftChildIndex].CompareTo(Items[RightChildIndex]) < 0)
swapIndex = RightChildIndex;
if (Item.CompareTo(Items[swapIndex]) < 0)
Swap(Item, Items[swapIndex]);
else
return;
}
else
return;
}
}
void SortUp(T Item)
{
int ParentIndex = (Item.HeapIndex - 1) / 2;
while (true)
{
T ParentItem = Items[ParentIndex];
if (Item.CompareTo(ParentItem) > 0)
Swap(Item, ParentItem);
else
break;
ParentIndex = (Item.HeapIndex - 1) / 2;
}
}
void Swap(T ItemA, T ItemB)
{
Items[ItemA.HeapIndex] = ItemB;
Items[ItemB.HeapIndex] = ItemA;
int itemAIndex = ItemA.HeapIndex;
ItemA.HeapIndex = ItemB.HeapIndex;
ItemB.HeapIndex = itemAIndex;
}
}
}