用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c代码库

堆排序 c算法

2012-10-31 作者: 程序猿style举报

[c]代码库

#include<stdio.h>
 
#include<stdlib.h>
#include<time.h>
 
#define MAX 10
#define SWAP(x,y) {int t;t=x;x=y;y=t;}
 
void createheap ( int[] );
void heapsort ( int[] );
 
int main ( void )
{
    int number[MAX+1]={-1};
    int i,num;
 
    srand ( time ( NULL ) );
 
    printf ( "排序前:" );
    for ( i=1; i<=MAX; i++ )
    {
        number[i]=rand() %100;
        printf ( "%d",number[i] );
    }
 
    printf ( "\n建立堆积树:" );
    createheap ( number );
    for ( i=1; i<=MAX; i++ )
        printf ( "%d",number[i] );
    printf ( "\n" );
 
    heapsort ( number );
 
    printf ( "\n" );
 
    return 0;
}
 
void createheap ( int number[] )
{
    int i,s,p;
    int heap[MAX+1]={-1};
 
    for ( i=1; i<=MAX; i++ )
    {
        heap[i]=number[i];
        s=i;
        p=i/2;
        while ( s>=2&&heap[p]>heap[s] )
        {
            SWAP ( heap[p],heap[s] );
 
            s=p;
            p=s/2;
        }
    }
 
    for ( i=1; i<=MAX; i++ )
        number[i]=heap[i];
 
}
 
void heapsort ( int number[] )
{
    int i,m,p,s;
 
    m=MAX;
    while ( m>1 )
    {
        SWAP ( number[1],number[m] );
        m--;
 
        p=1;
        s=2*p;
 
        while ( s<=m )
        {
            if ( s<m&&number[s+1]<number[s] )
                s++;
            if ( number[p]<=number[s] )
                break;
            SWAP ( number[p],number[s] );
            p=s;
            s=2*p;
        }
 
        printf ( "\n排序中:" );
        for ( i=MAX; i>0; i-- )
            printf ( "%d",number[i] );
    }
}

[代码运行效果截图]


堆排序 c算法


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...