0

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;
        }
Andrew
  • 1
  • 1
  • 1
    Can you show your driver function? The function where you order elements in heap by calling the constructor from n/2 to 0 indexes. – Rakesh Nov 13 '18 at 07:49
  • What do you mean by "without properly ordering the numbers?" Are you expecting the array to be sorted? – Jim Mischel Nov 13 '18 at 13:34

0 Answers0