import java.util.
ArrayList;
import java.util.Collections;
import java.util.List;
public class CustomHeap {
private List<Integer> heap;
private int childrenCount;
public CustomHeap(int x) {
this.childrenCount = (int) Math.pow(2, x); // 2^x children per node
this.heap = new ArrayList<>();
public void insert(int value) {
heap.add(value);
heapifyUp(heap.size() - 1);
public int popMax() {
if (heap.isEmpty()) {
throw new IllegalStateException("Heap is empty");
int max = heap.get(0);
heap.set(0, heap.get(heap.size() - 1));
heap.remove(heap.size() - 1);
heapifyDown(0);
return max;
}
private void heapifyUp(int index) {
while (index > 0) {
int parentIndex = (index - 1) / childrenCount;
if (heap.get(index) > heap.get(parentIndex)) {
Collections.swap(heap, index, parentIndex);
index = parentIndex;
} else {
break;
private void heapifyDown(int index) {
while (index < heap.size()) {
int largest = index;
for (int i = 1; i <= childrenCount; i++) {
int childIndex = childrenCount * index + i;
if (childIndex < heap.size() && heap.get(childIndex) > heap.get(largest)) {
largest = childIndex;
if (largest != index) {
Collections.swap(heap, index, largest);
index = largest;
} else {
break;
}
}
public void printHeap() {
System.out.println(heap);
public static void main(String[] args) {
CustomHeap heap = new CustomHeap(2); // 2^2 = 4 children per node
heap.insert(10);
heap.insert(20);
heap.insert(15);
heap.insert(30);
heap.insert(25);
heap.printHeap(); // [30, 25, 15, 10, 20]
System.out.println("Max: " + heap.popMax()); // Max: 30
heap.printHeap(); // [25, 20, 15, 10]