PackageKpp.sort;/**@authorKPP **/ Public classHeapsort { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub intArray[] = {49,38,65,97,176,213,227,49,78,34,12,164,11,18,1}; Heapsort (array); for(intK:array) {System.out.println (k); } } /*** Heap Sort *@paramArray*/ Public Static voidHeapsort (int[] Array) { //Building the initial heapbuildheap (array); intn =Array.Length; for(inti=n-1;i>=1;i--){ //swap heap top element and last unordered elementSwap (array,0, i); //re-adjust the rest of the heapAdjustheap (array,0, i); } } /*** Build a heap *@paramArray*/ Public Static voidBuildheap (int[] Array) { intn = array.length;//the number of elements in the array for(inti=n/2-1;i>=0;i--) Adjustheap (array,i,n); } /*** Adjustment Heap *@paramA *@paramCurrent Element *@paramend current need to adjust the last leaf node subscript of the heap*/ Public Static voidAdjustheap (int[] A,intCurrentintend) { intleft = 2*current+1;//The subscript of the left child (if present) intRight =2*current+2;//The subscript of the left child (if present) intlargest = 0;//looking for the subscript of the maximum node in 3 nodes if(Left<end && a[left]>A[current]) largest=Left ; Elselargest=Current ; if(Right<end && a[right]>A[largest]) largest=Right ; if(largest!=Current ) {swap (a,largest,current); Adjustheap (A,largest,end); } } /*** Heap top element and last unordered element interchange *@paramArray *@paramI *@paramJ*/ Public Static voidSwapint[] Array,intIintj) { intTemp =0; Temp=Array[i]; Array[i]=Array[j]; ARRAY[J]=temp; }}
Heap Sort Java Implementation