As shown below:
import java.util.Arrays;//The code of the small top heap implements public class Heap {// Adjust downward, the maximum value at the top is down, which is mainly used to delete and build the heap. i represents the node index to be adjusted, n represents the most element index of the heap.// When deletion, i is 0. When building the heap, i adjusts forward from the parent node of the last node public static void fixDown(int[] data, int i, int n) {int num = data[i];int son = i * 2 + 1;while (son <= n) {if (son + 1 <= n && data[son + 1] < data[son])son++;if (num < data[son])break;data[i] = data[son];i = son;son = i * 2 + 1;}data[i] = num;}// Adjust upward, small value goes upward, used to increase, and adjust upward does not require setting the top index, it is definitely 0public static void fixUp(int[] data, int n) {int num = data[n];int father = (n - 1) / 2;// data[father] > num is the basic condition for entering the loop. If the father decreases to 0, it will not decrease // When n is equal to 0, father=0; enters the dead loop, so when n==0, you need to jump out of the loop while (data[father] > num && n != 0) {data[n] = data[father];n = father;father = (n - 1) / 2;}data[n] = num;}// Delete, n represents the index of the last element of the heap public static void delete(int[] data, int n) {data[0] = data[n];data[n] = -1;fixDown(data, 0, n - 1);}// Increase, i represents the number to be added, n represents the index of the position to be added, it is the last element of the heap public static void insert(int[] data, int num, int n) {data[n] = num;fixUp(data, n);}// Build the heap, n represents the index of the last element of the heap public static void creat(int[] data, int n) {for (int i = (n - 1) / 2; i >= 0; i--)fixDown(data, i, n);}public static void main(String[] args) {int[] data = { 15, 13, 1, 5, 20, 12, 8, 9, 11 };// Test heap creat(data, data.length - 1);System.out.println(Arrays.toString(data));// Test delete(data, data.length - 1);delete(data, data.length - 2);System.out.println(Arrays.toString(data));// Test insert(data, 3, data.length - 2);System.out.println(Arrays.toString(data));}}The above article on Java implementation heap operation (building heap, inserting, deleting) is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.