Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Тема работы:

Адресация памяти и хранение переменных в стеке и куче (heap).


Мой коммит:

Код:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

// Class representing the "Max Heap" data structure


class Heap {
private List<Integer> heap; // List to store heap elements

// Constructor: Initializes an empty heap


public Heap() {
this.heap = new ArrayList<>();
}

// 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");
}

int maxValue = heap.get(0); // Maximum value is at the root of the heap


int lastValue = heap.remove(heap.size() - 1); // Remove the last element

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;
}

// Returns the current size of the heap


public int size() {
return heap.size();
}

// Checks if the heap is empty


public boolean isEmpty() {
return heap.isEmpty();
}

// Helper method: Checks if an element at a given index has a parent


private boolean hasParent(int index) {
return index > 0;
}

// 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: Checks if an element at a given index has a left child


private boolean hasLeftChild(int index) {
return getLeftChildIndex(index) < heap.size();
}

// 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: Checks if an element at a given index has a right child


private boolean hasRightChild(int index) {
return getRightChildIndex(index) < heap.size();
}

// 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));
}

// Converts the heap to an array


public Integer[] toArray() {
return heap.toArray(new Integer[0]);
}
}

You might also like