How to implement solution with custom heap implementation in java - priority queue not maintaining order
I'm not sure how to approach Can someone help me understand I'm working with an scenario with my custom heap implementation in Java that's supposed to function as a priority queue... The question arises when I try to enqueue elements; they seem to be inserted correctly, but when I attempt to dequeue them, the order is not maintained as expected. For instance, I added the elements 5, 3, and 8, which should result in 3 being dequeued first (since it has the highest priority, being the minimum in a min-heap), but when I call dequeue, I get 8 instead. Hereβs the basic structure of my heap class: ```java class MinHeap { private int[] heap; private int size; private int capacity; public MinHeap(int capacity) { this.capacity = capacity; this.size = 0; heap = new int[capacity]; } public void insert(int element) { if (size == capacity) { throw new RuntimeException("Heap is full"); } heap[size] = element; size++; bubbleUp(size - 1); } private void bubbleUp(int index) { while (index > 0) { int parentIndex = (index - 1) / 2; if (heap[parentIndex] <= heap[index]) { break; } swap(parentIndex, index); index = parentIndex; } } public int dequeue() { if (size == 0) { throw new RuntimeException("Heap is empty"); } int root = heap[0]; heap[0] = heap[size - 1]; size--; bubbleDown(0); return root; } private void bubbleDown(int index) { while (true) { int leftChild = 2 * index + 1; int rightChild = 2 * index + 2; int smallest = index; if (leftChild < size && heap[leftChild] < heap[smallest]) { smallest = leftChild; } if (rightChild < size && heap[rightChild] < heap[smallest]) { smallest = rightChild; } if (smallest == index) { break; } swap(index, smallest); index = smallest; } } private void swap(int i, int j) { int temp = heap[i]; heap[i] = heap[j]; heap[j] = temp; } } ``` I've tried adding debug statements in both `bubbleUp` and `bubbleDown` methods to monitor the values of the elements during the swapping process, and they seem to work correctly. However, the question continues. I've confirmed that the size is being decremented correctly and that the elements are being added in the right order. I'm currently using Java 11, and the expected behavior is to always get the minimum element on dequeue. Is there something I'm missing in the logic for maintaining the heap property, or could it be an scenario with how I'm handling the capacity and size of the heap? I'm using Java 3.10 in this project. What's the correct way to implement this? I'm working in a Debian environment. Thanks, I really appreciate it!