void push_down(int* a, int indx,int count)
{
do
{
int leftindx=indx*2+1;
int rightindx=leftindx+1;
//在将indx所指的元素向下压的时候,将左右两个子节点中最大的,并且大于indx本身的向上提。
//如果没有可以上提的左右子节点,则结束。
if (leftindx<count && rightindx>=count)
{
if (a[indx]<a[leftindx])
{
int tmp=a[indx];
a[indx]=a[leftindx];
a[leftindx]=tmp;
indx=leftindx;
}
else
break;
}
else if (leftindx<count && rightindx<count)
{
if (a[leftindx]>a[rightindx])
{
if (a[indx]<a[leftindx])
{
int tmp=a[indx];
a[indx]=a[leftindx];
a[leftindx]=tmp;
indx=leftindx;
}
else
break;
}
else
{
if (a[indx]<a[rightindx])
{
int tmp=a[indx];
a[indx]=a[rightindx];
a[rightindx]=tmp;
indx=rightindx;
}
else break;
}
}
else
break;
} while (indx<count);
}
bool create_heap(int* a, int count)
{
if (a==NULL)
return false;
if(count<0)
return false;
if (count==0 || count==1)
{
return true;
}
for (int i=(count-1)/2;i>=0;--i)
{
push_down(a,i,count);
}
return true;
}
bool heap_sort(int* a, int count)
{
if(a==NULL)
return false;
if (count<0)
return false;
else if(count==0 || count==1)
return true;
for (int i=count-1;i>0;--i)
{
int t=a[0];
a[0]=a[i];
a[i]=t;
push_down(a,0,i);
}
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
srand(time(0));
int size=rand()%4;
int *head=new int[size];
generate_n(head,size,genInt);
copy(head,head+size,ostream_iterator<int>(cout," "));
cout<<endl;
if (create_heap(head,size))
{
copy(head,head+size,ostream_iterator<int>(cout," "));
cout<<endl;
heap_sort(head,size);
copy(head,head+size,ostream_iterator<int>(cout," "));
cout<<endl;
}
getchar();
return 0;
}
1. 下压的时候,上提左右子树中最大的,并且大于本身的。
2. 输入输出参数。