码迷,mamicode.com
首页 > 编程语言 > 详细

堆排序

时间:2019-03-04 12:45:39      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:pac   turn   第一个   space   --   swa   for   max   scan   

#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=1e5+5;
int a[maxn], n;

void adjust(int s, int t) {
    int dad=s;
    int son=dad*2;
    while(son<=t)                               //自上而下循环调整 
    {
        if(son+1<=t && a[son]<a[son+1]) son++;
        if(a[dad]>a[son])   return;
        else
        {
            swap(a[dad], a[son]);
            dad=son;
            son=dad*2;
        }
    }
}
 
void heap_sort(int len)
{
    for(int i=len/2; i>=1; i--) adjust(i, len); //从最后一个有孩子的结点开始adjust 
    for(int i=len; i>=1; i--)                   //第一个和最后一个交换 
    {
        swap(a[1], a[i]);
        adjust(1, i-1);
    }
}

int main() {
    scanf("%d", &n);
    for(int i=1; i<=n; i++) scanf("%d", &a[i]); 
    heap_sort(n);
    for(int i=1; i<=n; i++) cout<<a[i]<<' ';
    cout<<endl;
    return 0;
}

堆排序

标签:pac   turn   第一个   space   --   swa   for   max   scan   

原文地址:https://www.cnblogs.com/lfyzoi/p/10469872.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!