Chinaunix首页 | 论坛 | 博客
  • 博客访问: 288679
  • 博文数量: 148
  • 博客积分: 4365
  • 博客等级: 上校
  • 技术积分: 1566
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-05 21:38
文章分类
文章存档

2014年(2)

2013年(45)

2012年(18)

2011年(1)

2009年(54)

2008年(28)

我的朋友

分类: C/C++

2009-09-17 12:24:51

#define SIZE 10

int array[SIZE]={6,8,7,9,0,1,3,2,5,4};
void Heap_Adjust(int *array,int low,int high){//堆排序调整堆算法

    int i=low,j=2*i+1; //应为j=2*i+1,可j=2*i也能正确,奇怪,毕竟下标从0开始

    int temp=array[i];
    while(j<=high)
    {
        temp=array[i];
        if((j<high)&&(array[j]<array[j+1]))
        {
            j++;
        }
        if(temp<array[j])
        {
            array[i]=array[j];
            array[j]=temp;
            i=j;
            j=2*i+1;
        }
        else break;
    }
}

void Heap_Sort(int *array,int n){//堆排序算法,不稳定 O(n*logn)

    int i,temp;
    for(i=n/2;i>=0;i--)
//不为i>=0,就有问题,如i>0,i>1;i=0时才排跟节点,即a[0]
        {
        Heap_Adjust(array,i,n);
        for(int h=0;h<SIZE;h++)
            cout<<" "<<array[h];
        cout<<" ad i= "<<i<<endl;
        }
    for(int i=0;i<SIZE;i++)
        cout<<" "<<array[i];
    cout<<" init"<<endl;
    for(i=n;i>0;i--)
    {
        temp=array[0];
        array[0]=array[i];
        array[i]=temp;
        Heap_Adjust(array,0,i-1);
        for(int k=0;k<SIZE;k++)
            cout<<" "<<array[k];
        cout<<" i= "<<i<<endl;
    }
}
int main(void) {
    Heap_Sort(array,9);
    for(int i=0;i<SIZE;i++)
        cout<<" "<<array[i];

    puts("\nHello World!!!");
    return EXIT_SUCCESS;
}

程序结果为

 6 8 7 9 4 1 3 2 5 0 ad i= 4
 6 8 7 9 4 1 3 2 5 0 ad i= 3
 6 8 7 9 4 1 3 2 5 0 ad i= 2
 6 9 7 8 4 1 3 2 5 0 ad i= 1
 9 8 7 6 4 1 3 2 5 0 ad i= 0
 9 8 7 6 4 1 3 2 5 0 init
 8 6 7 5 4 1 3 2 0 9 i= 9
 7 6 3 5 4 1 0 2 8 9 i= 8
 6 5 3 2 4 1 0 7 8 9 i= 7
 5 4 3 2 0 1 6 7 8 9 i= 6
 4 2 3 1 0 5 6 7 8 9 i= 5
 3 2 0 1 4 5 6 7 8 9 i= 4
 2 1 0 3 4 5 6 7 8 9 i= 3
 1 0 2 3 4 5 6 7 8 9 i= 2
 0 1 2 3 4 5 6 7 8 9 i= 1
 0 1 2 3 4 5 6 7 8 9
Hello World!!!

阅读(561) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~