Restudying, basic review (binary heap sequencing)
Minimum heap (the data of the final array is descending), maximum heap (the data of the final array is ascending)
The following example is 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);p rintf ("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 NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Restudying, basic review (binary heap sequencing)