堆排序中(小根堆的建法)
2005-11-30 16:29
204 查看
void Sift(int a[],int i,int n) //sift down.
{
int j = 0;
while((j = 2*i+1)<n)
{
if(j<n-1&&a[j]>a[j+1]) j++;
//now a[j] is the min of the triple.
//exchange the node
if(a[j]<a[i])
swap(a[j],a[i]);
i = j; //adjust to bottom.
}
}
void BuildHeap(int a[],int n)
{
for(int i=(n-1)/2;i>=0;i--)
Sift(a,i,n);
}
void HeapSort(int a[],int n)
{
BuildHeap(a,n); //Now a[0] is the smallest Elements.
for(int k=n-1;k>0;k--)
{
swap(a[0],a[k]);
Sift(a,0,k);
}
}
Heap sort times= 15 uMinutes
{
int j = 0;
while((j = 2*i+1)<n)
{
if(j<n-1&&a[j]>a[j+1]) j++;
//now a[j] is the min of the triple.
//exchange the node
if(a[j]<a[i])
swap(a[j],a[i]);
i = j; //adjust to bottom.
}
}
void BuildHeap(int a[],int n)
{
for(int i=(n-1)/2;i>=0;i--)
Sift(a,i,n);
}
void HeapSort(int a[],int n)
{
BuildHeap(a,n); //Now a[0] is the smallest Elements.
for(int k=n-1;k>0;k--)
{
swap(a[0],a[k]);
Sift(a,0,k);
}
}
Heap sort times= 15 uMinutes