Learn New, basic review (Binary heap sorting), learn new heap sorting

Source: Internet
Author: User

Learn New, basic review (Binary heap sorting), learn new heap sorting

Learn more, basic review (Binary heap sorting)

Minimum heap (the data in the final array is in descending order) and maximum heap (the data in the final array is in ascending order)


The following example shows the minimum heap.


#include <stdio.h>#include <stdlib.h>void Swap(int Arra[],unsigned int LeftIndex,unsigned int RightIndex){int TeampValue = Arra[LeftIndex];Arra[LeftIndex]=Arra[RightIndex];Arra[RightIndex]=TeampValue;}void MinHeapFixDown(int Arra[],unsigned int StartIndex,unsigned int ArraSize){int TeampValue = Arra[StartIndex];unsigned int MinValueIndexOfChild = 2*StartIndex+1;while(MinValueIndexOfChild<ArraSize){//printf("%u,%d,%d,%d\n",StartIndex,TeampValue,MinValueIndexOfChild,ArraSize);if (MinValueIndexOfChild+1<ArraSize&&Arra[MinValueIndexOfChild]>Arra[MinValueIndexOfChild+1]){MinValueIndexOfChild=MinValueIndexOfChild+1;}if (Arra[MinValueIndexOfChild]>=TeampValue){break;}Arra[StartIndex]=Arra[MinValueIndexOfChild];StartIndex=MinValueIndexOfChild;MinValueIndexOfChild=2*StartIndex+1;}Arra[StartIndex]=TeampValue;}void BuildMinHeap(int Arra[],unsigned int ArraSize){if (ArraSize<2){return;}//printf("build start\n");for (unsigned int i = (ArraSize-1)/2+1; i >0; --i){MinHeapFixDown(Arra,i-1,ArraSize);}//printf("build end\n");}void HeapSort(int Arra[],unsigned int ArraSize){BuildMinHeap(Arra,ArraSize);printf("ArraSize=%d\n",ArraSize);for (unsigned int i = ArraSize-1; i >=1; --i){Swap(Arra,0,i);MinHeapFixDown(Arra,0,i);}}int main(){//int Arra[]={-6,-8,9,-3,-1,0,13,-15,28,-40};int Arra[]={-6,10,-7,15,-9,12,50,-35,9};HeapSort(Arra,sizeof(Arra)/sizeof(Arra[0]));for (int i = 0; i < sizeof(Arra)/sizeof(Arra[0]); ++i){printf("%d,",Arra[i] );}printf("\n");}




Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.