#include<stdio.h> void swap(int *data, int old,int new){ int temp; temp = *(data+old); *(data+old) = *(data+new); *(data+new) = temp; } void heap(int *data,int location,int len){ int lchild = 2*location+1;//左孩子 int rchild = 2*location+2;//右孩子 int smallest = location; if(lchild < len && *(data+lchild) < *(data+smallest)) smallest = lchild; if(rchild < len && *(data+rchild) < *(data+smallest)) smallest = rchild; if(smallest != location ){ swap(data,smallest,location); heap(data,smallest,len); } } void init(int *data, int len){ //len/2 最大非葉子節點 int i; for( i =(len-1)/2;i>0;--i){ heap(data,i,len); } } int main(){ int data[7]={10,100,4,3,2,1,1000}; int i = 3; init(data,2); for(i=0; i < 2; i++){ printf("%d is %d\n",i,data[i]); } printf("-------------------\n"); for(; i < 7; i++){ if(data[i] <= data[0])continue; else{ swap(data,i,0); heap(data,0,2); } } for(i=0; i < 2; i++){ printf("%d is %d\n",i,data[i]); } }