数据结构——堆排

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dpdpd/article/details/79996806

数据结构笔记

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int a[100];
void adjust(int rt, int n)
{
    int child, rootkey;
    int temp;
    temp = a[rt];
    rootkey = a[rt];
    child = 2 * rt;
    while (child <= n)
    {
        if ((child < n) && (a[child] < a[child + 1]))
            child++;
        if (rootkey > a[child])
            break;
        else
        {
            a[child / 2] = a[child];
            child *= 2;
        }
    }
    a[child / 2] = temp;

}
void heapsort(int n)
{
    int i, j;
    int temp;
    for (i = n / 2; i>0; i--)
        adjust(i, n);
    for (i = n - 1; i>0; i--)
    {
        temp = a[1];
        a[1] = a[i + 1];
        a[i + 1] = temp;
        adjust(1, i);
    }
}
int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 1; i <=n; i++)
        scanf("%d", &a[i]);
    heapsort(n);
    for (int i = 1; i <=n; i++)
        printf("%d", a[i]);
}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页