Max Heap MaxHeapify Java Not finishing

35 views Asked by At

Having trouble with the constructor for MaxHeapify when there are more than 2 numbers that need to be ordered. stepping thru the code, it works for the first few and then continues without properly ordering the numbers. i am not sure why this isn't working, any assistance on which variables or comparisons I seem to be mixing up here would be much appreciated.

public class MaxHeap
{
    public int[] heap;
    public int index_to_last_element;

protected void maxHeapify(int index)
        {

            int left = leftchild(index);
            int right = rightchild(index);
            int largest = index;

            if (left < index_to_last_element && left != -1 && heap[left] > heap[index])
                largest = left;

            if (right < index_to_last_element && right != -1 && heap[right] > heap[largest])
                largest = right;

            if (largest != index)
                {
                    int temp = heap[index];
                    heap[index] = heap[largest];
                    heap[largest] = temp;

                    maxHeapify(largest);
                }
        }

    public int parent(int pos)
        {
            return (pos - 1) / 2;
        }

    public int leftchild(int pos)
        {
            return 2 * pos + 1;
        }

    public int rightchild(int pos)
        {
            return 2 * pos + 2;
        }
0

There are 0 answers