Heap Ordering (Java implementation)

Source: Internet
Author: User

In the introduction of algorithms, heap sorting is mainly divided into the nature of Heap , the nature of maintenance heap, the construction of Heap, the algorithm of heap sorting .

the nature of the heap: Given the subscript I of a node, it is easy to calculate the subscript (pseudo code) of its parent node, left child, and right child:

PARENT (i)     return I/2 left(i)    return  2i right    (i)    return 2i+1

here for the subscript starting from the 1 array, but actually we are involved in the array is starting from 0 . To improve the pseudo-code above, you can use the shift to resolve its pseudo-code:

PARENT (i)     return (i-1) >>1 left(i)    return ((i+1) <<1)-1 Right    (i)      Return (i+1) <<1

The nature of the maintenance heap (max-heapify):

max-heapify (A, i)    = left (i);     = Right (i);     if l <= a.heap-size and a[l] > a[i]        = largest    else largest = i;     if R <= a.heap-size and A[r] > a[largest]        = R    if largest!=< c20> i        exchangea[i]witha[largest]        MAX-heapify (A, largest)

The nature of the maintenance heap is implemented in the Java language: Maxheapify.java

 PackageHeapsort; Public classmaxheapify { Public voidHeapadjust (int[] A,intIintLen) {                intL =Left (i); intR =Right (i); intlargest = i;//assume the parent node has a maximum value                if(L < len && A[l] > A[i]) {//left child value is greater than parent node valuelargest =l; }                if(R < len && A[r] > A[largest]) {//right child value is greater than parent node valuelargest =R; }                if(Largest! =i) {//Exchange A[i]witha[largest]            intTMP =A[i]; A[i]=A[largest]; A[largest]=tmp;        Heapadjust (A, largest, Len); }            }    Private intRight (inti) {//Right Child coordinates        return((i+1) <<1);//return 2*i+1;    }    Private intLeft (inti) {//left child coordinates        return((i+1) <<1)-1;//return 2*i;    }    }

The nature code of the test maintenance heap is: Maxheapifytest.java

 PackageHeapsort; Public classMaxheapifytest { Public Static voidMain (string[] args) {int[] A ={16, 4, 10, 14, 7, 9, 3, 2, 8, 1};//int[] a={5, 2, 4, 6, 1, 3, 2, 6};Maxheapify maxheapify =Newmaxheapify (); Maxheapify.heapadjust (A,1, a.length);  for(inti = 0; i < a.length; i++) {System.out.print (A[i]+" "); }    }}

Test results:

Build a heap (build-max-heapify):

Use the bottom-up method to convert an array of size n=a.length A[1..N] to the maximum heap using the procedure max-heapify. A proof: when an array is used to represent a heap that stores n elements , the leaf node subscript is floor (N/2) +1and Floor(N/2) +2,...,n. As you know, the elements in the Subarray A[floor (N/2) +1..N] are the leaf nodes of the tree. Each leaf node can be viewed as a heap containing only one element. The procedure build-max-heapify calls the max-heapify once for the other nodes in the tree. Its pseudo-code is as follows:

build-max-HEAP (A) a.heap-size = for i = Floor (A.LENGTH/2) Downto 1    MAX-heapify (A, I)

Implementing the Build-max-heapify function in the Java language is: Buildheap.java

 Package Heapsort;  Public class buildheap {    publicvoid buildmaxheap (int.[] A) {        for (int i = a.length/2-1; I >= 0; i--) {            new  maxheapify ();            Maxheapify.heapadjust (A, I, a.length);     }}}

The ability to test the build heap is Buildheaptest.java:

 package   Heapsort;  public  class   Buildheaptest { public  static  void   main (string[] args) {int  [] A = {4, 1, 3, 2, +, 9,, 8, 7};        Buildheap buildheap  =  Buildheap ();        Buildheap.buildmaxheap (A);  for  (int  i = 0; i < a.length; i++< Span style= "color: #000000;"        ) {System.out.print (A[i]  + "" ); }    }}

Test results:

Heap Sorting algorithm :

Initially, the heap sorting algorithm uses BUILD-MAX-HEAP to build the largest heap of input array A[1..N], where n=a.length. Because the largest element in the array is always in the root node a[1], by exchanging it with a[n], we can put the element in the correct position. At this point, if we remove the node n from the heap (which can be achieved by reducing the value of a.heap-size), the remaining nodes of the original root will still be the largest heap, and the new root node may violate the maximum team nature. To maintain the nature of the maximum heap, we have to invoke Max-heapify (a, 1) to construct a new maximum heap on the a[1..n-1]. The heap sorting algorithm repeats this process until the heap size drops from n-1 to 2.

heapsort (A)    BUILD-max-HEAP (A)    for i = a.length downto 2        Exchange a[ 1] with A[i]        = a.heapsize-1        MAX-heapify (A, 1)

Note : This section of the pseudo-code array starting from 1, to implement the pseudo-code, you want to change the subscript to 0 to start.

Implementing heap Ordering with Java code is Heapsort.java:

 PackageHeapsort; Public classHeapsort { PublicHeapsort (int[] A) {buildheap buildheap=Newbuildheap ();        Buildheap.buildmaxheap (A);  for(inti = a.length-1; i > 0; i--) {            //Exchange A[1]witha[i]            intTMP = A[0]; a[0] =A[i]; A[i]=tmp; //the nature of the maintenance heapMaxheapify maxheapify =Newmaxheapify (); Maxheapify.heapadjust (A,0, I);//A[0] is the root node.        }    }    }

The test heap sorting algorithm is Heapsorttest.java:

 package   Heapsort;  public  class   Heapsorttest { static  void   main (string[] args) {int  [] A = {4, 1, 3, 2, +, 9,, 8, 7};        Heapsort heapsort  = new   Heapsort (A);  for  (int  j = 0; j < A.length; j++< Span style= "color: #000000;"        ) {System.out.print (A[j]  + "" ); }            }}

Test results:

Heap Ordering (Java implementation)

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.