欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

树形结构的数据结构(9)—— 大顶堆与小顶堆

最编程 2024-08-14 20:40:10
...
package linearStructure.tree.heap; import java.util.ArrayList; import java.util.List; public class MaxTopHeap { //存储堆的数组 private int[] heap; //堆的最大存储容量 private int maxSize; //当前堆的存储数量 private int heapSize; public MaxTopHeap(int maxSize) { this.heap = new int[maxSize]; this.maxSize = maxSize; this.heapSize = 0; } // 判断是否为空的方法 public boolean isEmpty() { return heapSize == 0; } // 判断是否填满 public boolean isFull() { return heapSize == maxSize; } // 获取堆顶的值 public int peek() throws Exception { if (heapSize == 0) { throw new Exception("heap is empty"); } return heap[0]; } // 往堆中添加值 public void insert (int value) throws Exception { if (heapSize == maxSize) { throw new Exception("head is full"); } heap[heapSize] = value; heapSize++; buildMaxHeap(heap); } // 删除堆顶值 public int poll() throws Exception { if (heapSize == 0) { throw new Exception("heap is empty"); } int ans = heap[0]; swap(heap,0,--heapSize); buildMaxHeap(heap); return ans; } // 建大顶堆 private int[] buildMaxHeap(int[] array) { for (int i = (heapSize-2)/2; i >= 0; i--) { adjustDownToUp(array,i,heapSize); } return array; } private void adjustDownToUp(int[] array, int index, int length) { int temp = array[index]; for (int i = 2*index+1; i < length; i = 2*i+1) { if (i < length-1 && array[i] < array[i+1]) { i++; } if (temp >= array[i]) { break; } else { array[index] = array[i]; index = i; } } array[index] = temp; } // 交换元素值 private void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // 获取所有元素 public List<Integer> getAllElements() { List<Integer> ans = new ArrayList<>(); for (int i = 0; i < heapSize; i++) { ans.add(heap[i]); } return ans; } }