I have written a small snippet, to find the shortest path between two nodes in a Min Heap.
public int shortestPath(int i, int j)
{
int path = 0;
int hi = Math.max(i, j);
int lo = i + j - hi;
while (hi > lo)
{
hi = hi / 2;
path++;
}
if (hi == lo) return path;
while (hi != lo)
{
if (lo > hi) lo = lo / 2;
else hi = hi / 2;
path++;
}
return path;
}
Is there a better way to do this with better average case? Just learning.
Edit:
int[] arr = {0, 1, 2, 3, 4, 5, 6, 7};
To make it simple, lets say this array is a binary heap. The root is 1, and shortest path between lets say, 5 and 7 is given by shortestPath(5, 7).