Detailed heap sorting algorithm principle and Java version of code implementation _java

Source: Internet
Author: User

Overview
Heap Ordering is a sort of tree selection, which is an effective improvement of direct selection sort.
The heap is defined as follows: A sequence with n elements (k1,k2,..., kn), if and only if satisfied:

is called a heap. As you can see from the definition of the heap, the top element of the heap (that is, the first element) must be the smallest item (the small top heap) or the largest item (the large top heap).
If you store a heap in a one-dimensional array, the heap corresponds to a complete binary tree, and the value of all non-leaf nodes (nodes with children) is no greater than (or less than) the value of their children, and the value of the root node (the top element of the heap) is the smallest (or largest).
(a) Large top heap sequence: (96, 83, 27, 38, 11, 09)
(b) Small top heap sequence: (12, 36, 24, 85, 47, 30, 53, 91)

Initially, the sequence of n numbers to be sorted is considered to be a sequential two-tree (one-dimensional array storage binary tree), adjust their storage order to become a heap, and output the top element of the heap to get the smallest (or largest) element in n elements. Then the remaining n-1 elements are readjusted to make them a heap, outputting the top element of the heap, and getting the second small (or second) element of n elements. And so on, until you finally get an ordered sequence of n nodes. Call this process a heap sort.

Steps & Examples
implementing heap sorting solves two problems:
(1) How to build a heap of n-sorted numbers;
(2) How to adjust the remaining n-1 elements to make it a new heap after outputting the top element of the heap.
Build Heap method (small top heap):
The process of building a heap on an initial sequence is a process of filtering over and over again.
n A complete binary tree of nodes, the last node is the subtree of the N/2 node.
Filtering starts with a subtree of the root of the N/2 node (N/2 is the last node with a subtree), making the subtree a heap.
After that, the subtree of each node is filtered into a heap until the root node.
As the diagram builds the heap initial process
Unordered sequences: (49, 38, 65, 97, 76, 13, 27, 49)

(a) unordered sequence, initial binary tree, 97 (8/2=4 node) as the parent node of the last node (49).
(b) 97>=49, replace the position, and then filter on the last node of N/2 65.
(c) 13<=27 and 65>=13, replace 65 and 13, then replace 38 (both larger than it, no action required), and filter 49.
(d) 13<=38 and 49>=13, replacing positions of 49 and 13, 49>=27, replacing 49 and 27.
(e) Finally get a heap, 13 is the most decimal we get.
Method of adjusting heap (small top heap):
A heap with m elements, the output of the top element of the heap, left m-1 elements. Heap bottom elements are fed to the top of the heap, and the heap is destroyed only because the root node does not satisfy the nature of the heap.
The root node is exchanged with the smaller elements in the left and right subtree.
In exchange with Zuozi: If Shozi is broken, repeat method (2).
If you are swapping with the right subtree, if the right subtree is corrupted, repeat the method (2).
The above exchange operation is continued on the subtree which does not satisfy the nature of the heap, until the leaves are formed and the heap is built.
The adjustment heap only considers the broken node, and the other nodes do not need to be adjusted.

Code implementation (Java)
run the code in conjunction with the annotation to compare the example steps above.

Package com.coder4j.main; public class Heapsort {/** * adjusted to small top heap (result from large to small after sorting) * * @param array is the heap array to be adjusted * @param S is the position of the array element to be adjusted * 
    @param length is an array of lengths */public static void Heapadjusts (int[] array, int s, int length) {int tmp = Array[s];
    int child = 2 * s + 1;//The position of the Left children node System.out.println ("The node to be adjusted is: array[" + S + "] =" + tmp); while (Baby < length) {//child + 1 is the right kid for the current adjustment node//If there is a right child and is less than the left child, use the right child to compare with the node, otherwise use the left child if (children + 1
      < length && Array[child] > array[child + 1]) {child++;
      System.out.println ("array[" + child + "] =" + Array[child] + "to compare");
        If the smaller child child than this node is small if (Array[s] > Array[child]) {System.out.println ("child child is smaller than it, swap position");
        Array[s] = array[child];//moves the smaller child child up, replaces the current pending node S = child;//the node to be adjusted to move to the smaller child's original position array[child] = tmp; Child = 2 * s + 1;//continues to determine if the node to be adjusted needs to continue to adjust if (child >= length) {SyStem.out.println ("No Child, Adjustment over");
        else {System.out.println ("continue to compare with the new Child Child");
      }//Continue;
        else {System.out.println ("child is larger than it, adjust the end"); 
   break;//current to be adjusted node is less than its left and right children, no need to adjust, direct exit}}}/** * adjusted to large top heap (the result of sorting is small to large) * * @param array is an array of the heap to be adjusted * @param S is the position of the array element to be adjusted * @param length is the size of the array * */public static void Heapadjustb (int[] array, int s, int leng
    TH) {int tmp = Array[s];
    int child = 2 * s + 1;//The position of the Left children node System.out.println ("The node to be adjusted is: array[" + S + "] =" + tmp); while (children < length) {//child + 1 is the right kid for the current adjustment node//If there is a right child and is greater than the left child, use the right child to compare with the node, otherwise use the left child if (children + 1
      < length && Array[child] < Array[child + 1]) {child++;
      System.out.println ("array[" + child + "] =" + Array[child] + "to compare");
        If the larger child child than this node is larger if (Array[s] < Array[child]) {System.out.println ("child child is larger than it, swap position"); Array[s] = Array[child];Move the larger child up, replace the current pending node S = child;//the node to be adjusted to move to the older child's original position array[child] = tmp; Child = 2 * s + 1;//continues to determine if the node to be adjusted needs to continue to adjust if (child >= length) {System.out.println ("No children, adjust knot")
        Bundle ");
        else {System.out.println ("continue to compare with the new Child Child");
      }//Continue;
        else {System.out.println ("child is smaller than it, adjust the end");  break;//current to be adjusted node larger than its left and right children, no need to adjust, direct exit}}/** * Heap sort algorithm * * @param array * @param inverse true Order in reverse order, false for positive order/public static void Heapsort (Int[] Array, Boolean inverse) {//initial heap//Last node with child i =
    (length-1)/2, by which the nodes are adjusted upward to conform to the heap System.out.println ("initial heap start");
      for (int i = (array.length-1)/2; I >= 0; i--) {if (inverse) {heapadjusts (array, I, array.length);
      else {heapadjustb (array, I, array.length);
    } System.out.println ("Initial heap End"); for (int i = array.length-1 i > 0; i--) {//Exchange heap top element h[0] and the last element of the heap int tmp = Array[i];
      Array[i] = array[0];
      ARRAY[0] = tmp;
      After each exchange of the top element of the heap and the last element in the heap, the heap is adjusted to the if (inverse) {heapadjusts (array, 0, i);
      else {heapadjustb (array, 0, i);
    }} public static void Main (string[] args) {int[] array = {49, 38, 65, 97, 76, 13, 27, 49};
    Heapsort (array, false);
    for (int i:array) {System.out.print (i + "");

 }
  }

}

Run Result:

 
 

PS: The difference between heap sort and direct insert sort
to select the smallest key record from R[1..N], you must perform a n-1 comparison, and then select the smallest key record in R[2..N]. and need to do n-2 comparison. In fact, there are a number of comparisons that might have been done in the previous n-1 comparison, but because the comparison was not preserved in the previous n-2, the comparison was repeated during the latter sort of time.
Heap Sorting can save some of the comparison results by using a tree structure to reduce the number of comparisons.

Related Article

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.