Professional Documents
Culture Documents
Popova Daria IA-213 SO5
Popova Daria IA-213 SO5
Код:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// Inserts a new element into the heap and maintains the max heap property
public void insert(int value) {
heap.add(value); // Add the element to the end of the list
heapifyUp(); // Move the element up the heap to restore the property
}
// Extracts the maximum element from the heap and maintains the max heap
property
public int extractMax() {
if (isEmpty()) {
throw new IllegalStateException("Heap is empty");
}
if (!isEmpty()) {
heap.set(0, lastValue); // Replace the root with the last element
heapifyDown(); // Move the element down the heap to restore the property
}
return maxValue;
}
// Helper method: Returns the index of the parent node for a given index
private int getParentIndex(int index) {
return (index - 1) / 2;
}
// Helper method: Returns the value of the parent node for a given index
private int getParent(int index) {
return heap.get(getParentIndex(index));
}
// Helper method: Returns the index of the left child for a given index
private int getLeftChildIndex(int index) {
return 2 * index + 1;
}
// Helper method: Returns the value of the left child for a given index
private int getLeftChild(int index) {
return heap.get(getLeftChildIndex(index));
}
// Helper method: Returns the index of the right child for a given index
private int getRightChildIndex(int index) {
return 2 * index + 2;
}
// Helper method: Returns the value of the right child for a given index
private int getRightChild(int index) {
return heap.get(getRightChildIndex(index));
}