Importjava.util.Arrays; Public classHeapsort {/*** Locate the parent node of the element labeled I in the array at the subscript position where the array is located * *@paramI * The subscript of the element to be manipulated *@returnThe subscript position of the parent node of the element under index i in the array*/ Static intParentinti) {return((i + 1) >> 1)-1; } /*** Find the subscript position of the left child node in the array where the element labeled I is located * *@paramI * The subscript of the element to be manipulated *@returnThe left child node of the element labeled I is in the subscript position of the array*/ Static intLeftinti) {returnRight (i)-1; } /*** Locate the right child node of the element labeled I in the array at the subscript position where the array is located * *@paramI * The subscript of the element to be manipulated *@returnThe right child node of the element labeled I is positioned at the subscript position in the array*/ Static intRightinti) {return(i + 1) << 1; } Static voidSwapintArray[],intFirstintsecond) { inttemp =Array[first]; Array[first]=Array[second]; Array[second]=temp; } /*** The array of arrays in the root as the starting point of continuous size+1 elements to the big top heap, but only if the root of the left and right two subtrees trees are big top heap *@paramArray *@paramRoot *@paramsize*/ Static voidSelectmax (intArray[],intRootintsize) { intlargest =Root; intleft =Left (root); intright =Right (root); if(left <= size && Array[left] >Array[largest]) {Largest=Left ; } if(Right <= size && Array[right] >Array[largest]) {Largest=Right ; } if(Largest! =root) {Swap (array, largest, root); Selectmax (array, largest, size); } } /*** Build a heap * *@paramArray *@paramsize*/ Static voidMakeheap (intArray[],intsize) { if(Array = =NULL|| Size <= 0) { return; } for(inti = SIZE/2; I >= 0; i--) {Selectmax (array, I, size); } } /*** Heap Sort * *@paramArray*/ Static voidHeapsort (intarray[]) { if(Array = =NULL|| Array.Length = = 0) { return; } makeheap (Array, Array.Length-1); for(inti = array.length-1; I >= 1; i--) {Swap (array,0, i); Selectmax (Array,0, I-1); } } Public Static voidMain (string[] args) {int[] Array = {1, 2, 3, 4, 5, 6, 9, 8, 7, 10, 11, 1001, 991, 188, 188, 34, 34, 34, 33, 3, 4, 34, 343, 0 }; System.out.println ("Before sorting:"); System.out.println (arrays.tostring (array)); Heapsort (array); System.out.println ("After sorting:"); System.out.println (arrays.tostring (array)); }}
Simple implementation of heap sorting