package Heap; import javax.activation.MimeType; import java.util.Arrays; import java.util.Map; /** * @auther qwh * @create 2023-04-2023/4/12 22:09 */ public class MinHeap { int[] array; int size; public MinHeap(int capacity){ this.array = new int[capacity]; } public boolean isFull(){ return size == array.length; } /** * 获取堆顶元素 * @return */ public int peek(){ return array[0]; } public int pool(){ int delete = array[0]; swap(0,size-1); size--; down(0); return delete; } public int pool(int index){ int deleted = array[index]; swap(index,size-1); size--; down(index); return deleted; } public void replace(int replace){ array[0] = replace; down(0); } /** * 堆的尾部添加元素 * @param offered * @return */ public boolean offer(int offered){ if (size == array.length){ return false; } up(offered); size++; return true; } private void up(int offered) { int child = size;//孩子节点的下标 while (child>0){ int persent = (size-1)/2;//父节点的下标 if (offered<array[persent]){ array[child] = array[persent]; } else { break; } child = persent; } array[child] = offered; } private void heapify(){ for (int i = size/2-1;i>=0;i--){ down(i); } } private void down(int persent) { int left = persent*2+1; int right = left+1; int min = persent; if (left<size&&array[left]<array[min]){ min = left; } if (right<size&&array[right]<array[min]){ min = right; } if (min != persent){ swap(min,persent); down(min); } } private void swap(int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } public MinHeap(int []array){ this.array =array; this.size = array.length; heapify(); } public static void main(String[] args) { int[] array = {2, 3, 1, 7, 6, 4, 5}; MinHeap heap = new MinHeap(array); System.out.println(Arrays.toString(heap.array)); while (heap.size > 1) { //删除堆顶元素 heap.swap(0, heap.size - 1); heap.size--; heap.down(0); } System.out.println(Arrays.toString(heap.array)); } }
小根堆 java MinHeap
最新推荐文章于 2024-07-28 09:30:00 发布