zoukankan      html  css  js  c++  java
  • 排序练习【sdut 1582】【堆排序】

    排序

    Time Limit: 1000ms   Memory limit: 32678K  有疑问?点这里^_^

    题目描述

        给你N(N<=100)个数,请你按照从小到大的顺序输出。

    输入

        输入数据第一行是一个正整数N,第二行有N个整数。

    输出

        输出一行,从小到大输出这N个数,中间用空格隔开。

    示例输入

    5
    1 4 3 2 5

    示例输出

    1 2 3 4 5

    提示

    本来这道题目用普通的选择排序或者是冒泡排序都可以ac,但是为了练一练堆排序,用堆排序的方法做了一下,权且当做抛砖引玉~

    代码:

     1 //堆排序
     2 #include<iostream>
     3 #include<string>
     4 #include<string.h>
     5 #include<stdlib.h>
     6 #include<algorithm>
     7 using namespace std;
     8 void heapsort(int f[],int );
     9 void heapadjust(int f[],int s,int m);
    10 int main()
    11 {
    12     int n;
    13     cin>>n;
    14     int i;
    15     int f[10000];
    16     for(i=1;i<=n;i++)
    17         cin>>f[i];
    18     heapsort(f,n);
    19     for(i=1;i<=n;i++)
    20         {
    21             if(i==1)
    22                 cout<<f[i];
    23             else
    24             cout<<" "<<f[i];
    25         }
    26     cout<<endl;
    27     return 0;
    28 }
    29 void heapsort(int f[],int n)
    30 {
    31     int i;
    32     for(i=n/2;i>0;i--)
    33     {
    34         heapadjust(f,i,n);
    35     }
    36     for(i=n;i>1;i--)
    37     {
    38         int temp;
    39         temp=f[1];
    40         f[1]=f[i];
    41         f[i]=temp;
    42         heapadjust(f,1,i-1);
    43     }
    44 }
    45 void heapadjust(int f[],int s,int m)
    46 {
    47     int rc=f[s];
    48     for(int j=2*s;j<=m;j=j*2)
    49     {
    50         if(j<m&&f[j]<f[j+1])++j;
    51         if(rc>=f[j])break;
    52         f[s]=f[j];
    53         s=j;
    54     }
    55     f[s]=rc;
    56 }
    View Code
  • 相关阅读:
    mysql资料
    MySQL启动与关闭
    poj 2778 DNA Sequence
    poj 1625 Censored!
    zoj 3228 Searching the String
    hdu 4605 Magic Ball Game
    hdu 4610 Cards
    SGU 439 A Secret Book
    NOI2013
    NOI2014
  • 原文地址:https://www.cnblogs.com/kuangdaoyizhimei/p/3471976.html
Copyright © 2011-2022 走看看