/************ to sort a sequence with a full heap sort ************ **/import Java.util.Random; Public classHeapsort { Public Static voidMain (String args[]) {int[] A =New int[1050]; Initlist (a);//InitializePrintlist (a);//print a randomly generated sequence
System.out.println ();//print a line of space before or after sorting
NewHeapsort (). Heap_sort (a); Printlist (a);//print a sequence after sorting } /*********************heapsort****************** **/ Public voidHeap_sort (inta[]) { intLength =a.length; //Build a heapcreatheap (a,length); for(inti = length; i >0; i-- ){ //Put the smallest to the last side, and then reconstruct the small top heap inttemp = a[0]; a[0] = a[i-1]; A[i-1] =temp; Creatheap (A,i-1); } } /********************* structure Small top heap ********************* **/ Public voidCreatheap (intA[],intlength) { //starting from the last non-leaf node, gradually adjusting to construct a small top heap for(inti = length/2; I >=0; i--) {heapadjust (a,i,length); } } /************************* Adjustment Small Top heap ************************ **/ Public voidHeapadjust (intA[],intPosintlength) { //POS for the node to be adjusted, leftchild for the left child to adjust the node, rightchild for the right child with the adjustment node intLeftchild = pos*2; intRightchild = pos*2+1; intMin =POS; if(Leftchild<length && a[leftchild]<A[min]) {min=Leftchild; } if(Rightchild<length && a[rightchild]<A[min]) {min=Rightchild; } if(min!=pos) {//adjusts the current node, if there is a node smaller than the current node, the interchange inttemp =A[pos]; A[pos]=A[min]; A[min]=temp; //The swapped node may not meet the small top heap, then the swapped node is recursively adjusted//if the min==pos, that is, the above exchange process does not occur, it will not perform the process of sub-recursive adjustmentHeapadjust (a,min,length); } //Adjust the child node of the current node } Public Static voidInitlist (int[] a) {Random Intr=NewRandom (); for(inti =0; i < a.length; i + +) {A[i]=intr.nextint ( +); } } Public Static voidPrintlist (int[] a) { for(inti =0; i < a.length; i + +) {System. out. Print (a[i]+" "); } }}
Java implementation of heap ordering