Please comment on this.
class MinHeap<T> where T: IComparable
{
List<T> elements;
public MinHeap()
{
elements = new List<T>();
}
public void Add(T item)
{
elements.Add(item);
Heapify();
}
public void Delete(T item)
{
int i = elements.IndexOf(item);
int last = elements.Count - 1;
elements[i] = elements[last];
elements.RemoveAt(last);
Heapify();
}
public T PopMin()
{
if (elements.Count > 0)
{
T item = elements[0];
Delete(item);
return item;
}
//relook at this - should we just throw exception?
return default(T);
}
public void Heapify()
{
for (int i = elements.Count - 1; i > 0; i--)
{
int parentPosition = (i+1) / 2 - 1;
parentPosition = parentPosition >= 0 ? parentPosition : 0;
if (elements[parentPosition].CompareTo(elements[i])>1)
{
T tmp = elements[parentPosition];
elements[parentPosition] = elements[i];
elements[i] = tmp;
}
}
}
}
int parentPosition = (i+1) / 2 - 1;
but this seems wrong to me. As an example, the elements at index 6 and 7 both belong to the parent at index 3. Your formula results in 2 for index 6 and 3 for index 7 ((6+1) / 2 - 1
,7 / 2 - 1
,3 - 1
,2
and(7+1) / 2 - 1
,8 / 2 - 1
,4 - 1
,3
). The formula seems like it should instead beint parentPosition = i / 2;
instead (6 / 2 = 3
and7 / 2 = 3
). This is of course assuming integer division. \$\endgroup\$