PackageKpp.sort;/*** The heap is defined as follows: sequence of n elements {k0,k1,..., ki,..., k (n-1)} When and only if the next relationship is satisfied, called a heap. "ki<=k2i,ki<=k2i+1; or Ki>=k2i,ki>=k2i+1." (i=1,2,..., [N/2]) "If a one-dimensional array corresponding to this sequence (that is, a storage structure with a one-dimensional array for this sequence) is considered a complete binary tree, The value of each node in a fully binary tree is greater than or equal to any one byte value (if any), called the Big Top heap. The value of each node in a fully binary tree is less than or equal to the value of any one byte (if any), called the small top heap. Thus, if the sequence {k0,k1,..., K (n-1)} is a heap, then the top element of the heap (or the root of a complete binary tree) must be the minimum (or maximum) of n elements in the sequence. If each node in the heap is given an integer value label, the root node is marked as 0, for each node labeled I, its left child node (if present) is marked as 2*i+1, and its right child node (if present) is marked as 2*i+2, for a non-root node labeled I, Its parent node is marked (i-1)/2. With this tag, we are able to store the heap in an array, where the nodes are stored in the data so that they are labeled. * @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