Go [Algorithm practice every day] heap and heap sorting

Source: Internet
Author: User

Heap Sort and quick sort , merge sort are the common sort methods of time complexity O (N*LOGN). Before learning heap sequencing, let's first explain what is a two-fork heap in the data structure.

Definition of binary heap

The binary heap is a complete binary tree or is an approximate complete binary tree.

The binary stack satisfies two characteristics:

1. The key value of the parent node is always greater than or equal to (less than or equal to) the key value of any one of the child nodes.

2. The Saozi right subtree of each node is a binary heap (both the largest heap or the smallest heap).

The maximum heap when the parent node's key value is always greater than or equal to the key value of any one of the child nodes. The minimum heap when the key value of the parent node is always less than or equal to the key value of any one of the child nodes. Show a minimum heap:

Since several other heaps (two-item heap, Fibonacci Ponachi, etc.) are used less often, the two-fork heap is referred to as a heap.

Storage of Heaps

The heap is usually represented by an array, and the parent node of the I node is labeled (i–1)/2. The index of the left and right sub-nodes is 2 * i + 1 and 2 * i + 2 respectively. such as the No. 0 node of the left and right sub-nodes subscript 1 and 2 respectively.

Heap operation--Insert Delete

The following gives the "data structure C + + language description" in the minimum heap of the establishment of the insertion and deletion of the plot, and then give my implementation code, it is best to look at the figure before going to see the code.

The insertion of a heap

Each insertion is a new data placed at the end of the array. It can be found that from the parent node of this new data to the root node must be an ordered sequence, now the task is to insert this new data into this ordered data-it is similar to the direct insertion of a data into the ordered interval, in contrast to the vernacular classical algorithm series two Three implementations of direct insertion sorting it's not hard to write the adjustment code for the heap when inserting a new data:

  the newly added I node  whose parent node is (i-1)/2  void minheapfixup (int a[], int i)  {      int J, temp;            temp = A[i];      j = (i-1)/2;      Parent Node      while (J >= 0 && I! = 0)      {          if (A[j] <= temp) break              ;                    A[i] = a[j];     Move the larger sub-node down, replacing its sub-node          i = j;          j = (i-1)/2;      }      A[i] = temp;  }  

  

A shorter expression is:

void Minheapfixup (int a[], int i)  {for      (int j = (i-1)/2; (J >= 0 && I! = 0) && a[i] > A[j]; i = j, j = (i-1)/2)          Swap (A[i], a[j]);  }  

 

When inserting:

Add new data to the minimum heap nnum  void minheapaddnumber (int a[], int n, int nnum)  {      a[n] = nnum;      Minheapfixup (A, n);  }  

Removal of heaps

By definition, only the No. 0 data can be deleted at a time in the heap. To facilitate rebuilding the heap, the actual operation is to assign the value of the last data to the root node, and then start from the root node with a top-down adjustment. Adjust the first in the left and right son node to find the smallest, if the parent node than the smallest sub-node is also small to indicate that no adjustment is needed, the parent node and it will be exchanged and then consider the subsequent nodes. Equivalent to the "sinking" process of a data from the root node. The following code is given:

Starting  from the I-node adjustment, n is the total number of nodes starting from 0 the child nodes of the I node are computed as 2*i+1, 2*i+2  void Minheapfixdown (int a[], int i, int n)  {      int J, temp;< C4/>temp = A[i];      j = 2 * i + 1;      while (J < N)      {          if (j + 1 < n && a[j + 1] < A[J])//Find the smallest J + + in the left and right child              ;            if (A[j] >= temp) break              ;            A[i] = a[j];     Move the smaller sub-node upward, replacing its parent node          i = j;          j = 2 * i + 1;      }      A[i] = temp;  }  Delete the number of  void minheapdeletenumber (int a[], int n)  {      Swap (a[0], a[n-1])      in the minimum heap; Minheapfixdown (A, 0, n-1);  }  

  

Stacking arrays

After the heap has been inserted and deleted, consider how to heap a data. You need to get the data out of the array, one by one, to build the heap, no! Look at an array first, such as:

Obviously, for the leaf node, it can be thought that it is already a legitimate heap, namely 20,60, 65, 4, 49 are a legitimate heap. As long as you start from the a[4]=50 downward adjustment. Then take a[3]=30,a[2] = 17,a[1] = 12,a[0] = 9 to make a downward adjustment operation. These steps are shown:

Write the code for the stacked array:

Establish minimum heap  void makeminheap (int a[], int n)  {      for (int i = N/2-1; I >= 0; i--)          Minheapfixdown (A, I, N) ;  

At this point, the heap operation is all done (note 1), and then see how the heap is used to sort the data structure.

Heap Sort

The first thing you can see is that the No. 0 data in the heap after the heap is built is the smallest data in the heap. Remove this data and perform the next heap delete operation. So the No. 0 data in the heap is the smallest data in the heap, repeating the above steps until there is only one data in the heap to take out the data directly.

Since the heap is also modeled with an array, the first time the array is stacked, a[0] and a[n-1] are exchanged, and then the heap is restored to a[0...n-2. Swap a[0] with A[n–2] for the second time, then redo the heap for a[0...n-3], repeating such operations until a[0] and a[1] are exchanged. Because each time the smallest data is incorporated into the subsequent ordered interval, the entire array is ordered after the operation is completed. Sort of like a direct selection .

void Minheapsorttodescendarray (int a[], int n)  {      for (int i = n-1; I >= 1; i--)      {          Swap (a[i], a[0]); 
   minheapfixdown (A, 0, i);      }  }  

Note that using the minimum heap sort is a descending array, and you can use the maximum heap to get an incremented array.

Because the time complexity of each re-recovery heap is O (logn), the N-1-redo heap operation, together with the N/2-down adjustment in front of the heap, and the complexity of each adjustment time are O (logn). Two operation times added or O (N * logn). Therefore, the time complexity of heap sequencing is O (N * logn). STL also implements the related functions of the heap, you can refer to the "four heap heap of STL series".

Note 1 As a data structure, it is best to use classes to encapsulate their data and methods so that they are easy to operate and understandable. In addition, in addition to heap sorting to use the heap, there are many occasions can use the heap to facilitate and efficient processing of data, will be introduced in the future.

Original address: http://blog.csdn.net/morewindows/article/details/6709644

Go [Algorithm practice every day] heap and heap sorting

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.