码迷,mamicode.com
首页 > 其他好文 > 详细

堆排序

时间:2014-08-26 11:19:16      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   ar   div   log   amp   sp   

//堆排序
//①维护堆 
void max_heapify(int *ptr,int index,int len)
{
    index = index + 1;
    int left = index << 1;
    int right = (index << 1) + 1;
    int largest = index;
    if(left <= len && ptr[left - 1] > ptr[index - 1])
        largest = left;
    if(right <= len && ptr[right - 1] > ptr[largest - 1])
        largest = right;
    if(largest != index)
    {
        swap(&ptr[index - 1],&ptr[largest - 1]);
        max_heapify(ptr,largest-1,len);
    }
    
} 
//②建立堆
void build_max_heap(int* ptr,int len)
{
    for(int i = len >> 1; i >= 0; --i)
    {
        max_heapify(ptr,i,len); 
    }
} 
//③堆排序
void heapSort(int* ptr,int len)
{
    build_max_heap(ptr,len);
    for(int i = len - 1;i>0;--i)
    {
        swap(&ptr[0],&ptr[i]);
        max_heapify(ptr,0,i);
    }
} 


int main()

{
    int a[] = {2,23,45,1,8,2,0};
     for(int i =0; i <= 6; ++i)
    {
        std::cout << a[i] << " ";
    }
    cout << endl;
    //mergeSort(a,0,6);
    //quickSort(a,0,6);
    heapSort(a,7);
    for(int i =0; i <= 6; ++i)
    {
        std::cout << a[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}

 

堆排序

标签:style   blog   color   for   ar   div   log   amp   sp   

原文地址:http://www.cnblogs.com/yi-meng/p/3936692.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!