PackageTestpackage;Importjava.util.Arrays; Public classHeap {//build a big Top pile Public Static voidBuildmaxheap (int[] a) { for(intI= (A.LENGTH/2) -1;i>=0;i--) {Adjustdown (a,i,a.length); } } //Downward Adjustment Public Static voidAdjustdown (int[] A,intIintLen) { inttemp,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 nodeJ + +; if(a[j]<=temp)//The Kawai node is smaller than the initial value temp, indicating that a location was found Break; Else{A[i]=A[J];//if there is no termination, raise the value of the child node to II=j;//at the same time I descend to J this position}} A[i]=temp;//put temp in the final position } //Heap Sort Public Static voidHeapsort (int[] a) {buildmaxheap (a); for(inti=a.length-1;i>=0;i--) { intTemp=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 I represent } } //Floating Upward Public Static voidAdjustup (int[] A,inti) {inttemp,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; } //Insert Public Static int[] Insert (int[] A,intnum) { int[] b=New int[A.length+1]; inti,j; I=0; J=0; while(i<a.length) b[j++]=a[i++]; B[a.length]=num; Adjustup (b,a.length); returnb; } //Delete (regular when deleted, the top element of the heap is deleted) Public Static int[] Delete (int[] a) {intTemp=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]; inti,j; I=j=0; while(i<a.length-1) b[j++]=a[i++]; returnb; } Public Static voidMain (string[] args) {int[] a= {5,88,45,37,91,26,13,66,50}; Buildmaxheap (a); //Build a heapSystem.out.println (Arrays.tostring (a)); A=insert (a,77);//InsertSystem.out.println (Arrays.tostring (a)); A=delete (a);//Delete, only the top element of the heap can be deletedSystem.out.println (Arrays.tostring (a)); Heapsort (a); //SortSystem.out.println (Arrays.tostring (a)); }}
Heap + Build heap, insert, delete, sort +java implementation