Packagepractice;ImportEdu.princeton.cs.algs4.StdRandom; Public classTestmain { Public Static voidMain (string[] args) {int[] A =New int[20]; for(inti = 0; i < a.length; i++) { inttemp = (int) (Stdrandom.random () *100); A[i]=temp; } heapsrot.sort (a); for(inti = 1; i < a.length; i++) {//only from a[1] Start rowSystem.out.print (a[i]+ ""); } System.out.println (); }}classheapsrot{ Public Static voidSortint[] a) {intp =a.length; for(intK = P/2; K >= 1; k--) {//because nodes without child elements are not processed, only half of the elements are processedSink (A, k, p);//from bottom to top all (excluding nodes without child elements), node sinks once, entire array is stacked in order}//why not plug in and float like a priority queue, because it's quick to 20%~30% while(P > 1) {//and the priority queue pops up the largest element and deletes the action, rather than deleting the largest element to the endExch (A, 1,--p);//move the first one to the endSink (A, 1, p);//will be replaced by sinking down } } /** Sinking*/ Private Static voidSinkint[] A,intKintP) {//Compare elements to sub-elements, smaller than sub-elements, and the larger of the two, swapping positions while((2*k + 1) < P && ((A[k] < A[2*k + 1]) | | (A[k] < a[2*K] )) {if(A[2*k + 1] > A[2*k]) {Exch (A, K, 2*k + 1); k = 2*k + 1; } Else{Exch (A, k, 2*k); k =K;} } } /** Exchange*/ Private Static voidExch (int[] A,intIintj) {intt =A[i]; A[i]=A[j]; A[J]=T; }}
Algorithm Animation Demo
Http://www.cs.usfca.edu/~galles/visualization/HeapSort.html
Heap Sort Java Implementation