堆排序

void exchange(int &a,int &b);       //交换 
void Max_Heapify(int *,int,int);    //保持堆性质 
void Build_Max_Heapify(int *,int);  //建堆 
void Sort_Heap(int*,int);       // 堆排序 
void exchange(int &a,int &b) 
{ 
    int t; t = a ;a = b ; b =t ; 
} 
void Max_Heapify(int *heap, int i,int heapSize)               //heapSize :堆大小  
{ 
    int l = 2*i + 1;        //左子树下标 
    int r = 2*i + 2;      //右子树下标 
    int largest;           //最大节点下标 
    if(l < heapSize && heap[l] > heap[i]) 
        largest = l; 
    else 
        largest = i; 
    if(r < heapSize && heap[r] > heap[largest] ) 
        largest = r; 
    if(largest != i) 
    { 
        exchange (heap[i],heap[largest]);   
        Max_Heapify(heap,largest,heapSize); //保持以largest为根节点的子树满足堆性质 
    } 
     
} 
void Build_Max_Heapify(int *heap,int arraySize)             
{ 
    int i = (arraySize/2)-1;   //含有子树的根节点的下标,(下标最大的根) 
    for(; i>=0; i--) 
        Max_Heapify(heap,i,arraySize); 
} 
void Sort_Heap(int *heap,int arraySize)            
{ 
     
    int i = arraySize-1; 
    Build_Max_Heapify(heap,i); 
     
    for(; i>=1 ; i--) 
    { 
        exchange(heap[i],heap[0]); 
        Max_Heapify(heap,0,i-1); 
    } 
} 
int main() 
{ 
    int a[N]={1,24,35,6,8,75,89,45,44,5,345,23}; 
     
    int i; 
    Sort_Heap(a,N);     
    for(i=0; i<N; i++) 
        cout << a[i]<<" "; 
    cout <<endl; 
    return 0; 
} 
posted @ 2009-12-03 12:28  zedzhao  阅读(94)  评论(0编辑  收藏  举报