5. algorithm BASICS (heap sorting): 5. algorithm Basics

Source: Internet
Author: User

5. algorithm BASICS (heap sorting): 5. algorithm Basics

Heap sorting: first of all, you need to know what the heap here is. The Heap here is actually a binary tree. Is it a very good image? The Complete Binary Tree is a triangle from the beginning, it can also be seen as a "heap ".


I. array Conversion

So the first problem to be solved is to sort the array and how to convert it into a binary tree? Conversion Method

Array int a [], containing elements a [0], a [1], a [2], a [3] ...... and so on.

Convert to binary tree:



The figure is more vivid. In fact, it is arranged down from the top of the heap, but there is a principle that when the upper layer is not full, there will be no elements in the next layer, and the upper layer is limited to full, to the next layer.


Ii. How to perform heap sorting


So the second question comes, how can we sort it.

Before considering this problem, we need to do some preliminary work:


1. We know the element a [I] in a heap. Who is its parent node? What about left and right subnodes (if any )?

Through observation, it is not difficult to figure out that if the array sequence number is ranked from 0, the parent node of element a [I] (of course, when I is not equal to 0) is a [(I + 1)/2-1], and the left and right subnodes are a [2 * I + 1] and a [2 * I + 2];


2. introduce the concept of a large root stack.

Big root heap: all the jobs except the root node, a [I], must meet the requirements: a [PARENT (I)]> = a [I], Here parent (I) indicates the sub-value of the parent node of I. Obviously, if we change a tree into a large heap, we can get the maximum value of the current tree, that is, the value of the top node of the heap, which is known by the nature of the big root heap.


3. For a left and right subtree that is already the root node of a large root heap, how can we convert the binary tree with this node as the root into a large root heap?

Obviously, if the root node is larger than the left and right subnodes, it is already a large root node.


If the root node is smaller than the left and right subnodes, or is it smaller than one of them? We need to swap the largest child node with the root node. But this is not complete yet, because after the original root node is switched to its direct child node location, it may not necessarily meet the conditions of the big roots. If not, we need to continue our work;

Take a look at the following code:


/*** A new large root heap is formed when both the left and right subtree are a large root heap */void maxHeapIndex (int a [], int root, int maxSize) {// obtain the subscript int l = leftChildIndex (root) of the Left subnode; // obtain the subscript int r = rightChildIndex (root) of the right subnode ); // first, the default value of the maximum node is the current root node int largest = root; // If the left node exists and the value of the Left node is greater than the root node, if (l <= maxSize & a [l]> a [root]) {largest = l ;} // if the left node exists and the value of the right node is greater than the root node, mark the maximum value as if (r <= maxSize & a [r]> a [largest]) of the right node. {largest = r;} // After marking, if it is found that the maximum value is indeed not the root node, It is exchanged and handed Call it to check whether the root node after the switch meets the needs of the big root heap. if (root! = Largest) {swap (a + root, a + largest); maxHeapIndex (a, largest, maxSize) ;}/ ** switch */void swap (int *, int * B) {int tmp = * a; * a = * B; * B = tmp;}/** returns the subscript of the Left subnode */int leftChildIndex (int I) {return (I + 1) * 2-1;}/** returns the subscript of the right subnode */int rightChildIndex (int I) {return (I + 1) * 2 ;}

4. subscripts of nodes in the heap.

After 3rd, we have fixed the problem that the Left and Right decision trees are full of big data to form a new big data pile; so how can we make an unprocessed heap form a large heap? How can we find that the left and right subtree is a big heap? If the left and right subtree are not found, it is better to avoid left and right subtree, that is, the leaf node does not have left and right subtree. In other words, they are a natural single-node big root heap; therefore, the parent node of a leaf node meets all the three assumptions. What is the range of the parent node of a leaf node in a heap?


For a full-node Binary Tree, if there is an h-layer, for example, from middle to a [15], there are three layers. For a full-node Binary Tree of the h-layer, the number of nodes is 2*2 ^ h-1, 2 ^ h is the h power of 2, the number of leaf nodes is 2 ^ h, the number of other nodes except the leaf node is 2 ^ h-1. We can easily conclude that if the array subscript starts from 0, the subscript range of other nodes except the leaf node should be [0, 2 ^ H-2].


So we only need to start from the node 2 ^ H-2 position, that is, the last layer of the rightmost node. H has the following relationship with n for heap with n nodes in the h layer: h = the nearest integer not less than lgn, we can start from the 2 ^ H-2 position until the 0 position has been cyclically executed 3rd points to form a large heap:

/*** Generate a large root heap. Train of Thought: * Call maxHeapIndex in sequence from the rightmost node of the last layer **/void maxHeapBuild (int a [], int len) {// obtain the height int h = log2 (len); // obtain the maximum available value int max = (int) (pow (2, h)-2; // loop call for (int I = max; I> = 0; I --) {maxHeapIndex (a, I, len-1 );}} /*** get the Base Value of log2 */int log2 (int I) {// The ceil function returns an integer return (int) not less than a value) ceil (log (I)/log (2 ));}



Iii. Heap sorting process

After the above four steps, we can get a big root heap. The next task is to use the big root heap for sorting.


The only thing we can determine for a large heap is that the element at the top of the heap must be the largest element in the current heap, so we can exchange the elements on the top with the rightmost leaf node, that is, the last leaf node, and then take out the maximum value, and subtract the number of heap nodes by one, then we re-operate on the vertex, that is, the leaf node that has just been switched to the vertex position. 3. We re-turn the new heap into a large root heap, And then we cyclically execute the above operations in turn, until all elements in the heap are taken out, the elements from the beginning to the end are sorted in the ascending order.


The code in this step is simple:

/** Heap sorting: * perform maxHeapBuild first, make the root node the largest value * then swap the value of the root node and the last node * Then disconnect the last node (maxsize-= 1) * then perform maxheapify, at this time, the left and right subtree of the root node is still a large heap, so you only need maxheapify instead of maxHeapBuild * so that the loop from n-1 to 2 can be done */void maxHeapSort (int a [], int maxSize, int tmp []) {maxHeapBuild (a, maxSize); // nfor (int I = maxSize; I> 0;) {// cyclically n-1 swap (a, a + I ); tmp [I] = a [I]; I --; if (I = 0) {tmp [0] = a [0];} else {maxHeapIndex (a, 0, i); // logn executes the N-2 times} for (int I = 0; I <= maxSize; I ++) {a [I] = tmp [I];}


Iv. complexity of heap sorting time

For the heap sorting algorithm, let's take a brief look at its time complexity. The time complexity of a maxHeapBuild is n, then the maxHeapIndex time complexity of loop N-1 is nlogn, and the cyclic assignment operation complexity is n, therefore, the time complexity is nlogn.



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.