Problem Description
有n(n<=100)個整數(shù),已經(jīng)按照從小到大順序排列好,現(xiàn)在另外給一個整數(shù)x,請將該數(shù)插入到序列中,并使新的序列仍然有序。
Input
輸入數(shù)據(jù)包含多個測試實(shí)例,每組數(shù)據(jù)由兩行組成,第一行是n和m,第二行是已經(jīng)有序的n個數(shù)的數(shù)列。n和m同時為0標(biāo)示輸入數(shù)據(jù)的結(jié)束,本行不做處理。
Output
對于每個測試實(shí)例,輸出插入新的元素后的數(shù)列。
Sample Input
<pre style="font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; white-space: pre-wrap; word-wrap: break-word;">
3 3
1 2 4
0 0
</pre>
Sample Output
<pre style="font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; white-space: pre-wrap; word-wrap: break-word;">
1 2 3 4
</pre>
Author
lcy
Source
Recommend
lcy
問題簡述:輸入一個n(n<=100),說明有n個整數(shù),輸入n個整數(shù)時,應(yīng)該讓其從小到大排序好,向其中插入一個整數(shù)X,要求插入后能夠?qū)崿F(xiàn)變化后的數(shù)列仍然有序。
問題分析:我們只需要定義一個動態(tài)數(shù)組元素個數(shù)為n+1,將x賦值給第n+1個元素,將新的數(shù)列進(jìn)行冒泡排序,然后輸出即可。
ACC++代碼如下
#include<iostream>
using namespace std;
void bubble(int *a, const int n)
{
for (int l = 0; l < n - 1; l++)
{
for (int i = 0; i < n - 1; i++)
{
if (a[i] > a[i + 1])
{
int t = a[i + 1];
a[i + 1] = a[i];
a[i] = t;
}
}
}
}
void charu(int m, int *a, const int n)
{
a[n] = m;
bubble(a, n + 1);
for (int i = 0; i <= n; i++)
{
cout << a[i];
if (i != n)
{
cout << ' ';
}
}
cout << endl;
}
int main()
{
int n, m;
while (cin >> n >> m)
{
int * p = new int[n+1];
if (n == 0 && m == 0)
{
break;
}
else
for (int i = 0; i < n; i++)
{
cin >> p[i];
}
charu(m, p, n);
}
return 0;
}