0% found this document useful (0 votes)
20 views2 pages

PowerOfTwoMaxHeap Java Implementation

The document contains a Java implementation of a Power of Two Max Heap data structure. It includes methods for inserting values, popping the maximum value, and maintaining the heap property through heapify operations. The constructor enforces a minimum branching factor of 2 for the heap.

Uploaded by

22tec2ee011
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views2 pages

PowerOfTwoMaxHeap Java Implementation

The document contains a Java implementation of a Power of Two Max Heap data structure. It includes methods for inserting values, popping the maximum value, and maintaining the heap property through heapify operations. The constructor enforces a minimum branching factor of 2 for the heap.

Uploaded by

22tec2ee011
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import [Link].

ArrayList;​
import [Link];​

public class PowerOfTwoMaxHeap {​

private final int branchingFactor;​
private List<Integer> heap;​

public PowerOfTwoMaxHeap(int branchingFactor) {​
if (branchingFactor < 2) {​
throw new IllegalArgumentException("Branching factor must
be at least 2");​
}​
[Link] = branchingFactor;​
[Link] = new ArrayList<>();​
}​

private int parent(int i) {​
return (i - 1) / branchingFactor;​
}​

private int leftChild(int i) {​
return i * branchingFactor + 1;​
}​

private int rightChild(int i) {​
return i * branchingFactor + 2;​
}​

private void swap(int i, int j) {​
int temp = [Link](i);​
[Link](i, [Link](j));​
[Link](j, temp);​
}​

private void heapifyDown(int i) {​
int largest = i;​
int left = leftChild(i);​
int right = rightChild(i);​

if (left < [Link]() && [Link](left) > [Link](largest))
{​
largest = left;​
}​

if (right < [Link]() && [Link](right) >
[Link](largest)) {​
largest = right;​
}​

if (largest != i) {​
swap(i, largest);​
heapifyDown(largest);​
}​
}​

private void heapifyUp(int i) {​
while (i > 0 && [Link](i) > [Link](parent(i))) {​
swap(i, parent(i));​
i = parent(i);​
}​
}​

public void insert(int value) {​
[Link](value);​
heapifyUp([Link]() - 1);​
}​

public int popMax() {​
if ([Link]()) {​
throw new IllegalStateException("Heap is empty");​
}​

int max = [Link](0);​
swap(0, [Link]() - 1);​
[Link]([Link]() - 1);​
heapifyDown(0);​

return max;​
}​
}​

You might also like