A heap is a complete binary tree, and the heap requirement is that the node is larger than its two child nodes. A two-byte point size is not necessarily.
The worst time complexity for heap sequencing is Nlog (n), an average of Nlog (n), and an O (1) footprint, which is a sort of comparison algorithm.
Heap sorting can also be used to find the maximum number of K. The time complexity is Klog (n), because after the heap is built, each loop actually generates a maximum number.
See the code below:
//sort from small to large Public classHeapsort {Private int[] A; Private intheapsize; //constructor, passing in the array to be sorted PublicHeapsort (int[] A) { This. A =A; } Public int[] Getsortedarray () {returnA; } //Starting from node I, so that the number of parent nodes is not less than the number of child nodes Private voidHeapify (inti) {//add 1, plus 2 is the node's two child nodes intleft = 2*i + 1; intright = 2*i + 2; intLargest = 0; //gets the largest number in the node, two child nodes if(Left < heapsize && A[left] >A[i]) {Largest=Left ; }Else{Largest=i; } if(Right < HeapSize && A[right] >A[largest]) {Largest=Right ; } //If the maximum number is not it, continue to build the heap, otherwise it will meet the heap requirements if(Largest! =i) {inttemp =A[i]; A[i]=A[largest]; A[largest]=temp; Heapify (largest); } } Private voidbuildheap () {heapsize=a.length; for(inti = (HEAPSIZE/2-1); I >= 0; i--) {heapify (i); } } Private voidHeapsort () {buildheap (); inttemp; for(inti = a.length-1; i > 0; i--) {Temp=A[i]; A[i]= A[0]; a[0] =temp; HeapSize--; Heapify (0); } } Public Static voidMain (string[] args) {
Test Casesint[] Array = {16,4,10,14,7,9,3,2,8,1,5,3,6,100}; Heapsort Heapsort=Newheapsort (array); Heapsort.heapsort (); for(inti:heapsort.a) {System.out.println (i); } }}
Implementation of Java heap sorting