C language implementation of heap sort algorithm based on maximum heap and minimum heap example _c language

Source: Internet
Author: User

Heap definition
The heap is actually a completely binary tree, and any one of its non-leaf nodes satisfies the nature:
KEY[I]<=KEY[2I+1]&&KEY[I]<=KEY[2I+2] (small top heap) or: key[i]>=key[2i+1]&&key>=key[2i+2] (large top pile)
That is, the keyword of any non-leaf node is not greater than or not less than the key word for its left and right child nodes.

The idea of heap sort
using the large top heap (small top heap) heap top record is the feature of the maximum keyword (the minimum key), making it easy to select the maximum record (minimum record) from the disorder each time.

    • Maximum heap: The child nodes of all nodes are smaller than their own heap.
    • Minimum heap: A heap of all nodes that have child nodes larger than themselves.

This is based on the largest heap, and its basic idea is:

1. The initial sequence of key sequences to be sorted (r1,r2 ...). Rn) is constructed into a large top heap, which is the initial disordered region;
2. Swap the heap top element r[1] with the last element R[n] to get the new unordered area (R1,R2,...... RN-1) and the new ordered region (RN), and satisfy the r[1,2...n-1]<=r[n];
3. Since the exchange of new heap top r[1] may violate the nature of the heap, it is necessary to the current unordered area (R1,R2,...... Rn-1) is adjusted to the new heap, and then again R[1] is exchanged with the last element of the unordered area to get the new unordered area (R1,R2 ...). Rn-2) and a new ordered region (RN-1,RN). Repeat this process until the number of elements in the ordered area is n-1, the entire sort process completes.

C Language Implementation
1. Ascending sorting based on maximum heap implementation

Initialize heap void initheap (int a[], int len) {//starting from the last non-child node of the complete binary tree////The index of the first element in the array is 0///n the left child of the element is 2n+1, the right child is 2n+2,//The last non child
 Node position in (n-1)/2 for (int i = (len-1)/2; I >= 0; i.) {ADJUSTMAXHEAP (A, Len, i); } void Adjustmaxheap (int a[], int len, int parentnodeindex) {//If there is only one element, then only the top element of the heap, and there is no need to reorder the if (Len <= 1) {RE
 Turn
 
 The index int targetindex =-1 for the left child or the right child that is larger than the parent node;
 Get the index of the left and right child int leftchildindex = 2 * parentnodeindex + 1;
 
 int rightchildindex = 2 * parentnodeindex + 2;
 There is no left child if (Leftchildindex >= len) {return;
 //There is a left child, but there is no right child if (Rightchildindex >= len) {targetindex = Leftchildindex; //have left child and right child else {//take left, right child both of the largest targetindex = A[leftchildindex] > a[rightchildindex]? leftchildindex:ri
 Ghtchildindex;
  
  //Only if the child is larger than the parent node, you need to exchange if (A[targetindex] > A[parentnodeindex]) {int temp = A[targetindex];
  A[targetindex] = A[parentnodeindex];
  
  
  A[parentnodeindex] = temp; After the exchange is complete, it is possible to cause A[targetindexThe subtree formed by the node does not satisfy the condition of the heap,//if the condition of the heap is not satisfied, then the adjustment makes it also the heap adjustmaxheap (A, Len, Targetindex);
 } void Heapsort (int a[], int len) {if (Len <= 1) {return;
 
 }///initial heap into unordered maximum heap initheap (A, Len); for (int i = len-1; i > 0 (i) {//swap the current heap top element with the last element to make sure that this trip finds the top element with the last element Exchange//NOTE: This is not the last a[len-1], but the range of every trip The last element//why should I add >0 judgment? Don't you think the top of the heap must be the maximum? Yes, after every adjustment, the top of the heap is the maximum///But, because Len's range is narrowing, causing some special sequences to appear abnormal//For example, 5, 3, 8, 6, 4 sequences, when adjusting i=1, has been adjusted to 3,4,5,6,8 sequence, has been ordered//But led to the a[
  I] exchange with a[0], because become 4,3,5,6,8 instead become disorderly!
   if (A[0] > A[i]) {int temp = a[0];
   A[0] = A[i];
  A[i] = temp; The//Range becomes://0...len-1//0...len-1-1//0...1//end//, where 0 is the top of the heap, each time you find an element that is larger than the top of the heap in the specified range, and then swap with the top element of the heap Adjustmax
 Heap (A, i-1, 0);
 }
}

2. Sort in descending order based on minimum heap implementation

Initialize heap void initheap (int a[], int len) {//starting from the last non-child node of the complete binary tree////The index of the first element in the array is 0///n the left child of the element is 2n+1, the right child is 2n+2,//The last non child
 Node position in (n-1)/2 for (int i = (len-1)/2; I >= 0; i.) {ADJUSTMINHEAP (A, Len, i); } void Adjustminheap (int a[], int len, int parentnodeindex) {//If there is only one element, then only the top element of the heap, and there is no need to reorder the if (Len <= 1) {RE
 Turn
 
 The index int targetindex =-1 for the left child or the right child that is larger than the parent node;
 Get the index of the left and right child int leftchildindex = 2 * parentnodeindex + 1;
 
 int rightchildindex = 2 * parentnodeindex + 2;
 There is no left child if (Leftchildindex >= len) {return;
 //There is a left child, but there is no right child if (Rightchildindex >= len) {targetindex = Leftchildindex; //have left child and right child else {//take left, right child two of the most targetindex = A[leftchildindex] < A[rightchildindex]? leftchildindex:ri
 Ghtchildindex;
  
  ///Only if the child is smaller than the value of the parent node, you need to exchange if (A[targetindex] < A[parentnodeindex]) {int temp = A[targetindex];
  A[targetindex] = A[parentnodeindex];
  
  
  A[parentnodeindex] = temp; After the exchange is complete, it is possible to cause A[targetindexThe subtree formed by the node does not satisfy the condition of the heap,//if the condition of the heap is not satisfied, then the adjustment makes it also the heap adjustminheap (A, Len, Targetindex);
 } void Heapsort (int a[], int len) {if (Len <= 1) {return;
 
 }///initial heap into unordered minimum heap initheap (A, Len); for (int i = len-1; i > 0 (i) {//swap the current heap top element with the last element to make sure that this trip finds the top element with the last element Exchange//NOTE: This is not the last a[len-1], but the range of every trip The last element//why should I add >0 judgment? Does it mean that the top of the heap must be the minimum value each time? Yes, after every adjustment, the top of the heap is the minimum///However, due to the narrowing of Len's range, causing some special sequences to appear abnormal//For example, 5, 3, 8, 6, 4 sequences, when adjusting i=1, has been adjusted to the 3,4,5,6,8 sequence, has been ordered//But led to the a[
  I] exchange with a[0], because become 4,3,5,6,8 instead become disorderly!
   if (A[0] < a[i]) {int temp = a[0];
   A[0] = A[i];
  A[i] = temp; The//Range becomes://0...len-1//0...len-1-1//0...1//end//, where 0 is the top of the heap, each time you find an element that is smaller than the top of the heap in the specified range, and then swap with the top element of the heap Adjustmin
 Heap (A, i-1, 0);
 }
}

3.C Language Edition Test

Everyone can test:

int a[] = {5, 3, 8, 6, 4};
int a[] = {89,-7,999,-89,7,0,-888,7,-7};
Heapsort (A, sizeof (a)/sizeof (int));
 
for (int i = 0; i < sizeof (a)/sizeof (int); ++i) {
  NSLog (@ "%d", A[i]);

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.