Skip to content

JAVA: Max Heap

Roberto Fronteddu edited this page Jul 12, 2024 · 3 revisions
public class MaxHeap {
    private int[] heap;
    private int size;
    private int maxSize;

    public MaxHeap(int maxSize) {
        this.maxSize = maxSize;
        this.size = 0;
        this.heap = new int[maxSize + 1];
        this.heap[0] = Integer.MAX_VALUE; // sentinel value to simplify finding parent, left and right child
    }

    private int parent(int pos) {
        return pos / 2;
    }

    private int leftChild(int pos) {
        return 2 * pos;
    }

    private int rightChild(int pos) {
        return 2 * pos + 1;
    }

    private boolean isLeaf(int pos) {
        return pos > size / 2 && pos <= size;
    }

    private void swap(int fpos, int spos) {
        int tmp = heap[fpos];
        heap[fpos] = heap[spos];
        heap[spos] = tmp;
    }

    // O(log n)
    private void heapify(int pos) {
        if (isLeaf(pos)) {
            return;
        }

        int l = leftChild(pos);
        int r = rightChild(pos);

        if (l <= size && (heap[pos] < heap[l] || (r <= size && heap[pos] < heap[r]))) {
            if (r > size || heap[l] > heap[r]) {
                swap(pos, l);
                heapify(l);
            } else {
                swap(pos, r);
                heapify(r);
            }
        }
    }
    // O (n), it looks O(log n) but each time is a limited search that approximates to O(n)
    public void buildHeap(int[] arr) {
        if (arr.length > maxSize) {
            throw new IllegalArgumentException("Input array size exceeds heap's maximum capacity");
        }

        size = arr.length;
        System.arraycopy(arr, 0, heap, 1, size); // Copy elements to heap array starting from index 1

        // Perform heapify on all non-leaf nodes
        for (int i = size / 2; i >= 1; i--) {
            heapify(i);
        }
    }

    public void insert(int element) {
        if (size >= maxSize) {
            System.out.println("Heap is full");
            return;
        }

        heap[++size] = element;
        int current = size;

        while (heap[current] > heap[parent(current)]) {
            swap(current, parent(current));
            current = parent(current);
        }
    }

    public int remove() {
        // remove and return max
        int popped = heap[1];
        heap[1] = heap[size--];
        heapify(1);
        return popped;
    }

    public void print() {
        for (int i = 1; i <= size / 2; i++) {
            System.out.print("PARENT : " + heap[i] + " LEFT CHILD : " + heap[2 * i]);
            if (2 * i + 1 <= size) {
                System.out.print(" RIGHT CHILD : " + heap[2 * i + 1]);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        System.out.println("Building max heap from array:");
        int[] arr = {4, 10, 3, 5, 1};
        MaxHeap maxHeap = new MaxHeap(arr.length);
        maxHeap.buildHeap(arr);
        maxHeap.print();
        
        System.out.println("\nInserting 15 into max heap:");
        maxHeap.insert(15);
        maxHeap.print();
        
        System.out.println("\nRemoving max from max heap:");
        maxHeap.remove();
        maxHeap.print();
    }
}
Clone this wiki locally