加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

【数据结构】堆积排序

发布时间:2020-12-15 05:59:35 所属栏目:安全 来源:网络整理
导读:题源:*航*系 数据结构作业 【问题描述】对一含有n个整数的数组,使用堆排序将其由小到大排序。 【输入形式】第一行为元素个数n,第二行为n个整数(以空格隔开)。 【输出形式】输出n个整数(以空格隔开) 【样例输入】 6 43 2 56 1 22 9 【样例输出】 1 2 9

题源:*航*系 数据结构作业


【问题描述】对一含有n个整数的数组,使用堆排序将其由小到大排序。
【输入形式】第一行为元素个数n,第二行为n个整数(以空格隔开)。
【输出形式】输出n个整数(以空格隔开)
【样例输入】
6
43 2 56 1 22 9
【样例输出】
1 2 9 22 43 56

============================================


#include <stdio.h>
#include <stdlib.h>

void adjust ( int a[],int i,int n );
void heapSort ( int a[],int n);

int main()
{
    int n;
    int i;
    int a[1024] = {0};

    scanf("%d",&n);
    for( i = 0; i < n; i++)
        scanf("%d",&a[i]);

    heapSort(a,n);

    for( i = 1; i <= n; i++)
        printf("%d ",a[i]);

    return 0;
}

void adjust ( int a[],int n ) {

    int j;
    int temp;

    temp = a[i];
    j = 2*i;

    while ( j <= n ) {

        if ( j < n && a[j] < a[j+1] )
            j++;

        if ( temp >= a[j] )
            break;

        a[j/2] = a[j];
        j = 2*j;

    }

    a[j/2] = temp;
}

void heapSort ( int a[],int n) {

    int i;
    int temp;

    for ( i = n/2; i >= 0; i--)
        adjust(a,i,n);

    for ( i = n-1; i >= 0; i--) {
        temp = a[i+1];
        a[i+1] = a[0];
        a[0] = temp;
        adjust(a,i);
    }
}





(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读