Java heap sorting and java heap sorting

Source: Internet
Author: User

Java heap sorting and java heap sorting

Heap is an important structure in the data structure. Understanding the concept and operation of "heap" helps us quickly grasp the heap sorting.

Concept of heap

Heap is a special complete binary tree ). If the value of all nodes in A Complete Binary Tree is no less than its subnodes, it is called a big root heap (or a big top heap). The value of all nodes is no greater than that of its subnodes, it is called a small root heap (or a small top heap ).

In the Array (store the root node in the subscript 0), it is easy to get the following formula (these two formulas are very important ):

1. Subscripts for I nodes, parent node coordinates (I-1)/2;

2. subscripts are I nodes. The coordinates of the Left subnode are 2 * I + 1, and the right subnode is 2 * I + 2.

Heap establishment and maintenance

Heap supports multiple operations, but now we only care about two problems:

1. How to Create a unordered array as a heap?

2. After deleting the heap top element, how can I adjust the array to become a new heap?

Let's look at the second question first. Suppose we already have a large ready-made root heap. Now we have deleted the root element, but it does not move any other element. Think about what happened: the root element is empty, but other elements are still heap. We can move the last element (codenamed A) to the position of the root element. Otherwise, the heap is damaged. However, this is only because A is smaller than A sub-element. Therefore, we can change the position of A and the child element. If A is greater than all its child elements, the heap is adjusted. Otherwise, repeat the above process and element A continues to "sink" in the tree structure until the appropriate position is reached, array to restore the properties of the heap. The above process is generally called "screening", and the direction is obviously top-down.

This is true for deleting an element, and for inserting a new element. The difference is that we put the new element at the end and compare it with its parent node, that is, bottom-up filtering.

So how can we solve the first problem?

Many of the data structures I have read are filtered down from the first non-leaf node until the root element is filtered out. This method is called the Limit Method and needs to filter n/2 elements cyclically.

However, we can also learn from the "out of nothing" idea. We can regard the first element as a heap and add new elements to it. This method is called the insert method. You need to insert (n-1) elements cyclically.

Because the filtering method and insertion method are different, the heap created for the same data is generally different.

After a general understanding of the heap, the heap sorting is just a matter of course.

Algorithm Overview/idea

What should we do if we need an ascending sequence? We can create a minimum heap and output the root element each time. However, this method requires extra space (otherwise it will cause a large number of elements to move, and its complexity will soar to O (n ^ 2 )). What should we do if we need to sort in place (that is, there is no O (n) space complexity allowed?
There is a way. We can create the largest heap, and then output the maximum value at the last position, and output the second heap at the last position ...... Since the maximum elements output each time will free up the first space, we can place such elements without extra space. Nice idea, isn't it?

1 public class HeapSort 2 {3 public static void main (String [] args) 4 {5 int [] arr = {50, 10, 90, 30, 70, 40, 80, 60, 20}; 6 System. out. println ("Before sorting:"); 7 for (int I = 0; I <arr. length; I ++) 8 System. out. print (arr [I] + ""); 9 10 // heap sorting 11 heapSort (arr); 12 System. out. println (); 13 System. out. println ("sorted:"); 14 for (int I = 0; I <arr. length; I ++) 15 System. out. print (arr [I] + ""); 16} 17 18 /** 19 * heap sorting 20 */21 private static void heapSort (int [] arr) 22 {23 // construct the sequence to be sorted into a large top heap 24 for (int I = arr. length/2; I> = 0; I --) 25 heapAdjust (arr, I, arr. length); 26 27 // gradually swap the root node of each maximum value with the end element, and then adjust the binary tree to make it a large top heap 28 for (int I = arr. length-1; I> 0; I --) 29 {30 swap (arr, 0, I ); // swap the heap top record with the last record of the unsorted subsequence 31 heapAdjust (arr, 0, I); // After switching, you need to re-check whether the heap meets the Big Top heap. If not, adjust 32} 33} 34/** 35 * heap construction process 36 * @ param. Array 37 * @ param I the number of the root node to which arr needs to sort is 38 * @ param n the length of the array 39 */40 private static void heapAdjust (int [] arr, int I, int n) 41 {42 int child; 43 int father; 44 for (father = arr [I]; leftChild (I) <n; I = child) 45 {46 child = leftChild (I); 47 // if the left subtree is smaller than the right subtree, You need to compare the right subtree with the parent node 48 if (child! = N-1 & arr [child] <arr [child + 1]) 49 child ++; // The serial number is increased by 1, pointing to the right subtree 50 // if the parent node is smaller than the child node, You need to exchange 51 if (father <arr [child]) 52 arr [I] = arr [child]; 53 else54 break; // The structure of the Big Top heap is not damaged and 55} 56 arr [I] = father is not required; 57} 58 59 // get left child node 60 private static int leftChild (int I) 61 {62 return 2 * I + 1; 63} 64 65 // switch element location 66 private static void swap (int [] arr, int index1, int index2) 67 {68 int tmp = arr [index1]; 69 arr [index1] = arr [index2]; 70 arr [index2] = tmp; 71} 72}

 

Author: xin, published in blog

Reprinted please indicate the source, welcome to mail exchange: zhuanxinxin@foxmail.com

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.