void maxheapify(int *data,int i){
int left = 2*i;
int right = 2*i+1;
int largest;
if(data[i]<data[left])
largest = left;
else
largest = i;
if(data[right]>data[largest])
largest = right;
if(largest!=i){
int temp = data[i];
data[i] = data[largest];
data[largest] = temp;
}
maxheapify(data,largest);
}
void initheap(int *data,int len){
for(int i = len/2;i>0;--i)
maxheapify(data,i);
}
void heapsort(int *data,int len){
initheap(data,len);
for(int i = len-1;i>1;--i){
int temp = data[0];
data[0] = data[i];
data[i] = temp;
maxheapify(data,0);
}
}
|