zoukankan      html  css  js  c++  java
  • 二、排序问题1

    2.1.1 题目中n<1000,故可以考虑使用冒泡排序O(n^2)

    程序中while (scanf ("%d",&n) != EOF )   //输入n并实现多组数据的输入

    若输入为字符串,则程序采用gets()的方法读入,相应的循环判断语句为while( get(字符串变量) );

    #include <stdio.h>
    
    int main () {
        int n;
        int a[100];//
        while (scanf ("%d",&n) != EOF ) { //输入n并实现多组数据的输入
            for (int i = 0;i < n;i ++) {
                scanf("%d",&a[i]);
            }
            for (int i = 0;i < n-1;i ++) {    //冒泡排序 
                for (int j = 0;j < n-i-1;j ++) {
                    if (a[j+1] < a[j]) {
                        int temp = a[j];
                        a[j] = a[j+1];
                        a[j+1] = temp;
                    }
                }
            }
            for (int i = 0;i < n;i ++) {
                printf("%d ",a[i]);
            }
            printf("
    ");//输出换行 
        }
        return 0; 
    } 

    2.1.2 若n值大于3000,则O(n^2)超过百万数量级,应使用快排

    C++中有快速排序库函数,添加algorithm头文件

    #include <stdio.h>
    #include <algorithm>
    using namespace std;
     int main () {
         int n;
         int a[10000];
         while (scanf("%d",&n) != EOF ) {
             for(int i = 0;i < n;i ++) {
                 scanf("%d",&a[i]);
             } 
             sort (a,a+n);    //快速排序
             for(int i = 0;i < n;i ++) {
                 printf("%d ",a[i]);
             } 
             printf("
    ");
         }
         return 0;
     } 

    2.1.3 同时,可以定义sort()函数中第三个参数,进行降序排列

    新定义一个cmp函数,实现新的排序规则定义,当cmp返回值为true时,表示cmp函数第一个参数排在第二个参数前面。

    #include <stdio.h>
    #include <algorithm>
    using namespace std;
    
    bool cmp(int x,int y){    //自定义排序函数
        return x > y;
    }
    int main () {
        int n;
        int a[10000];
        while (scanf("%d",&n) != EOF) {
            for(int i = 0;i < n;i ++){
                scanf("%d",&a[i]);
            }
            sort(a,a + n,cmp);
            for(int i = 0;i < n;i ++){
                printf("%d ",a[i]);
            }
            printf("
    ");
            
        }
        return 0;
    }
  • 相关阅读:
    用纹理贴图模拟反射,NeHe23课球面映射相关
    VS2010: CommandLine Warning D9025
    【转】C RunTime Library 暨 深入理解编译选项的含义 01
    让Doxygen输出中文注释不乱码
    windows环境下memcache配置
    C#中英文字符长度截取
    apache 的工作原理
    pear包安装phpunit
    使用 libevent 和 libev 提高网络应用性能
    PHP发明人谈MVC和网站设计架构——貌似他不支持php用mvc
  • 原文地址:https://www.cnblogs.com/chao-zjj/p/8194536.html
Copyright © 2011-2022 走看看