package testpackage; import java.util.Arrays; public class Heap { //建立大顶堆 public static void buildMaxHeap(int[] a) { for(int i=(a.length/2)-1;i>=0;i--) { adjustDown(a,i,a.length); } } // adjust down public static void adjustDown( int [] a, int i, int len) { int temp,j; temp = a[i]; for (j=2*i+1;j<len;j=2*j+1) { // j is the child node of the current i, the default is the left node if (j+1< len&&a[j+1]>a[j]) // If the right node is large, select the right node j++ ; if (a[j]<=temp) // If the child nodes are smaller than the initial value temp, it means that the position has been found break ; else { a[i] =a[j]; // If there is no termination, then adjust the large value in the child node to i at i=j; // At the same time, i drops to the position of j } } a[i] = temp; // put temp in the final position } // heap sort public static void heapSort( int [] a) { buildMaxHeap(a); for(int i=a.length-1;i>=0;i--) { int temp=a[0]; a[0]=a[i]; a[i]=temp; adjustDown(a, 0,i); // Adjust the remaining len-1 to a large top heap, loop, so use i to represent } } // float up public static void adjustUp( int [] a, int i) { int temp,j; temp=a[i]; j=(i-1)/2; while(j>=0&&a[j]<temp) { a[i]=a[j]; i=j; j = (j-1)/2 ; } a[i]=temp; } //插入 public static int[] insert(int[] a,int num) { int[] b=new int[a.length+1]; int i,j; i=0; j=0; while(i<a.length) b[j++]=a[i++]; b[a.length]=num; adjustUp(b,a.length); return b; } // Delete (there are rules when deleting, the top element of the heap will be deleted) public static int [] delete( int [] a) { int temp=a[0 ]; a[0]=a[a.length-1]; a[a.length-1]=temp; adjustDown(a,0,a.length-1); int[] b=new int[a.length-1]; int i,j; i=j=0; while(i<a.length-1) b[j++]=a[i++]; return b; } public static void main(String[] args) { int[] a= {5,88,45,37,91,26,13,66,50}; buildMaxHeap(a); //建堆 System.out.println(Arrays.toString(a)); a=insert(a,77); //插入 System.out.println(Arrays.toString(a)); a =delete(a); // Delete, only the top element of the heap can be deleted System.out.println(Arrays.toString(a)); heapSort(a); //排序 System.out.println(Arrays.toString(a)); } }