Implementation of Java heap sorting

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.