0% found this document useful (0 votes)
3 views3 pages

Import Java

The document contains a Java implementation of a custom heap data structure that allows for a specified number of children per node. It includes methods for inserting values, popping the maximum value, and maintaining the heap properties through heapify operations. The main method demonstrates the functionality by inserting values and printing the heap before and after popping the maximum value.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

Import Java

The document contains a Java implementation of a custom heap data structure that allows for a specified number of children per node. It includes methods for inserting values, popping the maximum value, and maintaining the heap properties through heapify operations. The main method demonstrates the functionality by inserting values and printing the heap before and after popping the maximum value.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

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]

You might also like