Problem 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
代码:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt(); // n(n<=100)个整数
int m = sc.nextInt(); // 插入整数x
int arc[] = new int[n + 1];
if (n == 0 && m == 0) {
System.exit(0);
}
arc[n] = m;
for (int i = 0; i < n; i++) {
arc[i] = sc.nextInt();
}
Arrays.sort(arc);
//遍历结果
for (int i = 0; i < n + 1; i++) {
if (i == 0) {
System.out.print(arc[i]);
} else
System.out.print(" " + arc[i]);
}
System.out.println();
}
}
}


本文介绍了一个简单的算法,用于在一个已排序的整数序列中插入一个新的整数,保持序列的有序性。通过使用Java的Arrays.sort()方法,文章提供了一种有效的方法来实现这一功能。示例代码展示了如何读取输入数据,进行排序并打印结果。
238

被折叠的 条评论
为什么被折叠?



