Need Some Help with Binary Heaps

So I’ve been reading this article on binary heaps and trying to incorporate it in my pathfinding code but have no luck. I was hoping to get some feedback on my attempt to see what went wrong:

void SortedAdd (Node nextNode) {

	if(open.Count < 1){
		open.Add(new Node());
		return;
	}

	open.Add(nextNode);

	int index = open.IndexOf(nextNode);
	int parentIndex = Mathf.RoundToInt(index/2);
	float fCost = nextNode.f;

	while(fCost > open[parentIndex].f){
		if(fCost > open[parentIndex].f){
			Swap(nextNode, open[parentIndex]);
			int opIndex = parentIndex;
			parentIndex = Mathf.RoundToInt(opIndex/2);
		}else{
			break;
		}
	}
}

void Swap (Node n1, Node n2) {

	int n1ind = open.IndexOf(n1);
	int n2ind = open.IndexOf(n2);
	open[n1ind] = n2;
	open[n2ind] = n1;
}

When I checked the open list, the nodes were not in order therefore the path was all over the place. Any idea where I went wrong?

This code definitely can’t do what you want. Suppose for instance that open currently has four values - 1,4,5 and 7, for instance - and you’re going to add value 3: the new element is created at index 4 and parentIndex becomes 2; since the new element is lower than open[2], the value 3 is left at index 4, which is obviously wrong.

If you want to implement a binary insertion algorithm yourself, take a look at this article to get the basics - or post a link to the article you’ve mentioned in the question.