Explanation of heap sort algorithm and implementation of Java version _java

Source: Internet
Author: User

Heap is an important structure in data structure, understand the concept and operation of "heap", can grasp heap sort quickly.

The concept of a heap
The heap is a special kind of complete binary tree (complete binary). If the value of all nodes of a completely binary tree is not less than its child nodes, it is called a Dagen (or a large top heap); All nodes have a value that is less than its child nodes, called a small Gan (or a small top heap).
The following formula (which is important for the two equations) is easy to get in the array (in the subscript No. 0 Storage root node):
1. The node labeled as I, the parent node coordinates (I-1)/2;
2. The node with subscript I, the left child node coordinate is 2*i+1 and the right child node is 2*i+2.

The establishment and maintenance of the heap
The heap can support a variety of operations, but now we only care about two things:
1. Given an unordered array, how do you build it as a heap?
2. How do I resize an array to become a new heap after removing the top element of the heap?
Let's look at the second question first. Suppose we already have a large pile of ready-made. Now we delete the root element, but we don't move any other elements. Think about what happened: The root element is empty, but the other elements remain the nature of the heap. We can move the last element (code a) to the position of the root element. If it is not a special case, the nature of the heap is destroyed. But this is only because a is less than one of its child elements. So, we can swap a and this child element position. If a is greater than all of its child elements, the heap is adjusted; otherwise, repeat the above procedure, the a element continues to "sink" in the tree structure until the appropriate location, the array to restore the nature of the heap. These processes are generally referred to as "filtering", with the direction clearly top-down.
Deleting an element is so, as is inserting a new element. The difference is that we put the new element at the end and then compare it to its parent, that is, bottom-up filtering.
So, how do we solve the first problem?
Many of the data structures I've read are filtered down from the first non-leaf node until the root element is filtered. This method is called "filtering" and requires a circular filtering of N/2 elements.
But we can also learn from the idea of "nothing". We can view the first element as a heap and then add the new element to it continuously. This method is called "Insert Method" and requires a circular insertion of (n-1) elements.
Because of the different ways of filtering and inserting methods, the same data, the heap they build, is generally different.

After roughly understanding the heap, the heap sort is the thing.

Algorithm Overview/ideas
We need an ascending sequence, what do we do? We can create a minimum heap and then output the root element each time. However, this method requires extra space (otherwise it will cause a lot of element movement and its complexity will soar to O (n^2)). What if we need to sort in place (that is, O (n) space complexity is not allowed)?
There is a way. We can build up the maximum heap, and then we output it backwards, output the maximum value in the last position, and then output the second large value at the end of the position. Because the largest element of each output frees up the first space, we can just place such an element without needing extra space. It's a pretty idea, isn't it?

public class Heapsort {public static void main (string[] args) {int[] arr = {50, 10, 90, 30, 70, 40, 80, 60, 
    20}; 
    System.out.println ("Sort before:"); 
    for (int i = 0; i < arr.length i++) {System.out.print (Arr[i] + ""); 
 
    }//Heap sort heapsort (arr); 
    System.out.println (); 
    System.out.println ("after sort:"); 
    for (int i = 0; i < arr.length i++) {System.out.print (Arr[i] + ""); }/** * Heap sort/private static void Heapsort (int[] arr) {//build the sequence to be sorted into a large top heap for (int i = a RR.LENGTH/2; I >= 0;  
    i--) {heapadjust (arr, I, arr.length); //gradually swap the root node of each maximum value with the end element, and then adjust the binary tree so that it becomes the large top heap for (int i = arr.length-1 i > 0; i--) {Swap (arr, 0, I); Exchanges the last record of the heap top record and the current unordered sequence Heapadjust (arr, 0, I); 
   After swapping, it is necessary to re-examine whether the heap conforms to the large top heap, and does not conform to the process of adjusting}/** * Build heap * @param arr the array to be sorted * @param i need the sequence number of the root node of the build heap * @param n-array length/private static void HEapadjust (int[] arr, int i, int n) {int child;  
    int father; 
       
      for (father = Arr[i], leftchild (i) < n; i = child) {child = Leftchild (i); If the Zoozi tree is smaller than the right subtree, you need to compare the right subtree and the parent node if (child!= n-1 && Arr[child] < Arr[child + 1]) {child++; 
      1, pointing to the right subtree}//If the parent node is smaller than the child nodes, you need to exchange if (Father < Arr[child]) {arr[i] = Arr[child]; 
  else {break;//large top heap structure not compromised, no adjustment}} Arr[i] = Father; 
  //Get to left child node private static int leftchild (int i) {return 2 * i + 1; 
    }//Exchange element position private static void swap (int[] arr, int index1, int index2) {int tmp = ARR[INDEX1]; 
    ARR[INDEX1] = Arr[index2]; 
  ARR[INDEX2] = tmp; 

 } 
}

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.