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

堆排序的实现

时间:2014-05-19 15:13:43      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   java   

bubuko.com,布布扣
#include<iostream>
using namespace std;
//大根堆,从小到达排序
int a[101];
void swap(int &a,int &b)
{
  a=a^b;
  b=a^b;
  a=a^b;
  


}
void adjust(int *a,int root,int len)
{
    int max=root;
    int left=2*root;
    int right=2*root+1;
    if(left<=len&&a[max]<a[left])
    {
        max=left;
    
    }

    if(right<=len&&a[max]<a[right])
    {
        max=right;
    
    }
    if(max!=root)
    {
        swap(a[max],a[root]);
        
      adjust(a,max,len);
    
    }



}
void bulidHeap(int *a,int len)
{


    for(int i=len/2;i>=1;i--)
    {
        adjust(a,i,len);
    
    
    }




}

void heapSort(int *a,int len)
{
    if(len>1)
    {
        swap(a[1],a[len]);
        adjust(a,1,len-1);//调整为堆
        heapSort(a,len-1);
    
    }



}
void output(int *a,int len)
{
    for(int i=1;i<=len;i++)
    {
        cout<<a[i]<<" ";
    
    }
    cout<<endl;

}

int main()
{
    
    while(!cin.eof())
    {
        int len;
        cin>>len;
        for(int i=1;i<=len;i++)
        {
          cin>>a[i];
        }
        
        bulidHeap(a,len);
        
        heapSort(a,len);
        output(a,len);
    
    
    
    }
    

    return 0;



}
bubuko.com,布布扣

堆排序的实现,布布扣,bubuko.com

堆排序的实现

标签:style   blog   class   code   c   java   

原文地址:http://www.cnblogs.com/hansongjiang/p/3735186.html

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