#include <iostream> #include <stdlib.h> #include <assert.h> #include <string.h> void siftDown(int * str, int start, int end); void heapify(int * str,int count); void heapSort(int * str, int count); void printStr(int * str, int count); void exchange(int * str, int a, int b); void printStr(int * str, int count) { for(int i=0;i<count;i++) { std::cout<<str[i]<<" "; } std::cout<<std::endl; } void exchange(int * str, int a, int b) { str[a]=str[a]+str[b]; str[b]=str[a]-str[b]; str[a]=str[a]-str[b]; } void heapSort(int * str, int count) { heapify(str, count); int end=count-1; while(end>0) { exchange(str,0,end); end--; siftDown(str,0,end); } } void heapify(int * str,int count) { int start=(count-2)/2; while(start>=0) { siftDown(str,start,count-1); start--; } } void siftDown(int * str, int start, int end) { int root=start; int swap; int child; while(root*2+1<=end) { child=root*2+1; swap=root; if(str[swap]<str[child]) { swap=child; } if(child+1<=end&&str[swap]<str[child+1]) { swap=child+1; } if(swap!=root) { exchange(str,swap,root); root=swap; } else { return; } } } int main() { int str[8]={6,8,1,7,4,5,3,2}; heapSort(str,8); printStr(str,8); }