HDU2019数列有序!

Time Limit: 2000/1000 MS (Java/Others)

Memory Limit: 65536/32768 K (Java/Others)

Description
有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序。
Input
输入数据包含多个测试实例,每组数据由两行组成,第一行是n和m,第二行是已经有序的n个数的数列。n和m同时为0标示输入数据的结束,本行不做处理。
Output
对于每个测试实例,输出插入新的元素后的数列。
Sample Input

3 3
1 2 4
0 0

Sample Output

1 2 3 4

Hint
lcy
Source
  C语言程序设计练习(三)  
Related problem
2015 2016 2023 2012 2022

如题,可以用链表也可以用数组,这里只给出数组的做法,就是在输入数据后去遍历数组,a[i]<m<a[i+1]时,后面的数往后面挪,腾个位置给m。

代码如下:

#include <iostream>
using namespace std;

int main()
{
int n,m,a[105];
while(cin >> n >> m,n != 0 && m != 0)
{
for(int i=0;i<n;i++)
    cin>>a[i];
for(int i=0;i<n;i++)
{
    if(a[i]<=m&&a[i+1]>=m)
    {
        for(int j=n;j>i;j--)
            a[j]=a[j-1];
        a[i+1]=m;    
        break;
}
}
    for(int i=0;i<=n;i++)
 {       
       cout<<a[i];
        if(i<n)
            cout<<" ";
        else 
            cout<<endl;
    }
}
}

猜你喜欢

转载自blog.csdn.net/qq_41627235/article/details/82801003