zoukankan      html  css  js  c++  java
  • 在有顺序的数列中插入一个元素后该数列仍然是有顺序的数组

    /**

     在有顺序的数组中插入一个元素后该数列仍然是有顺序的数组:

     思路:先找到该元素的插入位置

          插入数据时要先将数组中得元素后移,然后插入该元素

     */

    #include <stdio.h>

    #define  n 10

     int main()

    {

        // 在有顺序的数列中插入一个元素后该数列仍然是有顺序的数列:

        int a[n] = {-1, 3, 6, 9, 13, 22, 27, 32, 49};

        int insertVal;

        int insertLoc;

        scanf("%d", &insertVal);

            // 找到插入的数在数组中得位置

        for (int i = 0; i<9; i++) {    

            if (insertVal>a[i] && insertVal<a[i+1]) { // 该元素在数列元素中

                            insertLoc = i+1;    

                // 插入到该位置,(需要将该位置后面的值后置,然后插入该值)

                for (int j =n-1; j>i+1; j--) {

                    a[j] = a[j-1];

                }

                a[i+1] =insertVal;

            }else if (insertVal < a[n-10]){ // 该元素在第一位置

                insertLoc = n-10;

                for (int j = n-1; j>0; j--) {      

                    a[j] = a[j-1];

                }

                a[0] = insertVal;

             }else if (insertVal > a[n-2]){ // 该元素在最后面

                insertLoc = n-1;

                a[n-1] = insertVal;

            }

        }

    // 输出

        for (int i = 0; i <n; i++) {

               printf("%d ", a[i]);

        }

        printf(" ");  

        return 0;

    }

  • 相关阅读:
    docker 容器启动初始化,centos镜像启动并执行
    odoo 分布式session 失效解决方案
    文件分布式存储 minio docker
    odoo reports 报表打印pdf初探
    odoo 分布式快速更新
    linux Warning: Stopping docker.service, but it can still be activated by:
    linux 查看80端口的连接数
    css flex 涨姿势了
    odoo 后台打印日志修改
    iOS 导航栏消失
  • 原文地址:https://www.cnblogs.com/-boy/p/4020520.html
Copyright © 2011-2022 走看看