18052 插入数据

18052 插入数据

Description
已经有一个按升序排列的数组,编写程序输入一个整数x,把x插入到数组中,使数组仍然保持升序。
数组如下:
2 3 5 7 11 13 17 23 29 31 34 71 79 97 103

#include <stdio.h>
int a[16]={2, 3, 5, 7, 11, 13, 17, 23, 29, 31, 34, 71, 79, 97, 103};
void display()
{
int i;
for(i=0; i<16; i++) printf("%d ", a[i]);
}
int main()
{


display();
return 0;

}
输入格式
输入一个整数x

输出格式
输出更新后的数组元素

输入样例
5

注意细节!

AC代码1:从前往后遍历(太繁琐!)


#include <iostream>
#include <cstdio>
#include <math.h>

using namespace std;

int a[16]={2, 3, 5, 7, 11, 13, 17, 23, 29, 31, 34, 71, 79, 97, 103};
void display()
{
    int i;
    for(i=0; i<16; i++) printf("%d ", a[i]);
}
int main()
{
    int x,t;
    scanf("%d",&x);
    for(int j = 0;j < 15;j++){
        if(x <= a[j] ){
            t = a[j+1];
            a[j+1] = a[j];
            a[j] = x;
            x = t;
        }
        else if(x > a[14]){
            a[15] = x;
            break;
        }
    }
    display();
    return 0;
}


AC代码2:从后往前遍历

#include <iostream>
#include <cstdio>
#include <math.h>

using namespace std;

int a[16]={2, 3, 5, 7, 11, 13, 17, 23, 29, 31, 34, 71, 79, 97, 103};
void display()
{
    int i;
    for(i=0; i<16; i++) printf("%d ", a[i]);
}
int main()
{
    int x,j;
    scanf("%d",&x);
    for(j = 14;j >= 0;j--){ //从后往前遍历
        if(x < a[j] ){ //大于x的元素都往后靠
            a[j + 1] = a[j];
        }
        else break;//找到插入位置,退出循环
    }
    a[j+1] = x;//插入x
    display();
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值