I took a cource “Data structures” as part of my university studies, it is a real torture comparing to all previous cources , not to mention .NET courses ;-). But it is always good to know the basics. Now we are studing a heap and heapsort. A "heap" is a binary tree which has the property that each child is "smaller" (for an appropriate definition of "smaller"; this generally requires that the data type be totally ordered) than the parent. Another property is that left child of parent(i) is located index 2i, right child on 2i+1. The problem was to find efficient algorithm for searching the heap. I didn't find such one in the net. So I tryed to write it by my self, I am not sure if it is most efficient way so I am waiting for your feedbacks.
// pre: array must be a heap
private
static int search(int[] array, int i, int num)
{
if((i)>(array.Length))
return -1;
if((num>array[i-1]))
return -1;
if(array[i-1] == num)
return i;
return max(search(array,(2*i),num),search(array,(2*i)+1,num));
}
I couldn't make by iterative way, is it possible?