33,008
社区成员
发帖
与我相关
我的任务
分享
#define cmp(A, B) (A < B)
typedef long itemType;
void maxHeapify(itemType A[],int l,int r,int i){
/*
shiftDown
*/
if(i<l || i>r) return;
int root=i;
int largest=root;
int left=root-l+root+1;
int right=root-l+root+2;
if(right<=r && cmp(A[root],A[right]))
largest=right;
if(left<=r && cmp(A[largest],A[left]))
largest=left;
while(largest!=root){
itemType tmp=A[root];
A[root]=A[largest];
A[largest]=tmp;
root=largest;
left=root-l+root+1;
right=root-l+root+2;
if(right<=r && cmp(A[root],A[right]))
largest=right;
if(left<=r && cmp(A[largest],A[left]))
largest=left;
}
}
void buildMaxHeap(itemType A[],int l,int r){
for(int i=l-1+(r-l+1)/2;i>=l;i--)
maxHeapify(A,l,r,i);
}
void heapSort(itemType A[],int l,int r){
if(l==r) return;
buildMaxHeap(A,l,r);
int end=r;
while(end>l){
itemType tmp=A[end];
A[end]=A[l];
A[l]=tmp;
end--;
maxHeapify(A,l,end,l);
}
}