<span style="font-size:14px;">绝对不用递归,杜绝递归</span>
<span style="font-size:14px;">
</span>
<span style="font-size:14px;">#include<stdlib.h>
#include<stdio.h>
#include<string.h>
void HeapPass(int * a,int i,int len);
void MyHeapSort(int * a,int len,int * b);
int leftChild(int i);
int rightChild(int i);
void MyHeapSort(int * a,int len,int * b)
{
int * arr = (int *)malloc(sizeof(int) * len);
int i = len/2-1;
int j ;
for(;i>=0;i--)
{
HeapPass(a,i,len);
}
int arr_i = 0;
for(j= len -1 ;j>=0;j--)
{
arr[arr_i++] = a[0];
int temp = a[0] ;
a[0] = a[j];
a[j]= temp;
HeapPass(a,0,j);
}
memcpy(b,arr,sizeof(int)*len);
}
void HeapPass(int *a,int i,int len)
{
int left = leftChild(i);
int right = rightChild(i);
int isHeap = 0;
int root_value = a[i];
while(left<len && !isHeap)
{
if(right<len)
{
if(a[right]<a[left])
left = right;
}
if(a[i]<a[left])
isHeap = 1;
else
{
a[i] = a[left];
i = left ;
a[i] = root_value;
left = leftChild(i);
right=rightChild(i);
}
}
}
int leftChild(int i)
{
if(i==0)
return 1;
return i*2;
}
int rightChild(int i)
{
if(i==0)
return 2;
return i*2+1;
}</span>
<span style="font-size:14px;">Client:</span>
int main()
{
<span style="white-space:pre"> </span>//声明一个待排序数组
<span style="white-space:pre"> </span>int array[N];
<span style="white-space:pre"> </span>//设置随机化种子,避免每次产生相同的随机数
<span style="white-space:pre"> </span>srand(time(0));<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>for(int i=0 ; i<N ; i++)
{
array[i] = rand()%101;//数组赋值使用随机函数产生1-100之间的随机数
}
cout<<"排序前:"<<endl;
for(int j=0;j<N;j++)
{
cout<<array[j]<<" ";
}
cout<<endl<<"排序后:"<<endl;
//调用堆排序函数对该数组进行排序
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>MyHeapSort(array,N,array);
<span style="white-space:pre"> </span>
for(int k=0;k<N;k++)
{
cout<<array[k]<<" ";
}
cout<<endl;
return 0;
}