堆排序(可以作为模板)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_34952846/article/details/52937978

堆排序

#include <cstring>
#include <cstdio>
#include <algorithm>
#include <iostream>
using namespace std;

void heapAdjust ( int a[], int i, int size )
{
    int left_size = 2*i;
    int right_size = 2*i+1;
    int cnt = i;
    
    /*The rules of large Root Sort   大根堆的规则*/
    if ( i <= size/2 )
    {
        if ( left_size <= size && a[left_size] > a[cnt] )
            cnt = left_size;
        if ( right_size <= size && a[right_size] > a[cnt] )
            cnt = right_size;
            
        /*Overall adjustment Sort   对序列的整体调整*/
        if ( cnt != i )
        {
            swap( a[i], a[cnt] );
            heapAdjust ( a, cnt, size );
        }
    }
}

void buildHeap ( int a[], int size )
{
    int i;
    for ( i = size/2;i > 0; i-- )
    {
        heapAdjust ( a, i, size );
    }
}

void heapSort( int a[], int size )
{
    int i;

    /*To establish a large Root Sort under the initial state
                                                          建立初始状态下的大根堆*/
    buildHeap ( a, size );

    /*Adjust the Sort          调整序列*/
    for ( i = size;i > 0; i-- )
    {
        swap ( a[1], a[i] );
        heapAdjust ( a, 1, i-1 );
    }
}

int main()
{
    int size, i;
    int a[100];

    /*输入数据     Input data*/
    scanf ( "%d", &size );
    for ( i = 1;i <= size; i++ )
    {
        scanf ( "%d", &a[i] );
    }

    /*堆排序      Heap sort start*/
    heapSort( a, size );

    /*输出数据     Output data*/
    for ( i = 1;i <= size; i++ )
    {
        printf ( i == size ? "%d\n" : "%d ", a[i] );
    }
    return 0;
}

代码菜鸟,如有错误,请多包涵!!!

如有帮助记得支持我一下,谢谢!!!

展开阅读全文

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