我正在尝试使用N个随机数创建具有10个数字的行,这些随机数按递增顺序排序。我已设法创建一个包含N个随机数的数组,我也对它们进行了排序,但我不知道如何以10个数字的行打印它们。任何帮助将不胜感激。
这是我的N个随机数的代码:
public class Mergesort {
private static double[] merge(double[] a, double[] b) {
double[] c = new double[a.length + b.length];
int i = 0, j = 0;
for (int k = 0; k < c.length; k++) {
if (i >= a.length) c[k] = b[j++];
else if (j >= b.length) c[k] = a[i++];
else if (a[i] <= b[j]) c[k] = a[i++];
else c[k] = b[j++];
}
return c;
}
public static double[] mergesort(double[] input) {
int N = input.length;
if (N <= 1) return input;
double[] a = new double[N/2];
double[] b = new double[N - N/2];
for (int i = 0; i < a.length; i++)
a[i] = input[i];
for (int i = 0; i < b.length; i++)
b[i] = input[i + N/2];
return merge(mergesort(a), mergesort(b));
}
/***************************************************************************
* Check if array is sorted - useful for debugging.
***************************************************************************/
private static boolean isSorted(double[] a) {
for (int i = 1; i < a.length; i++)
if (a[i] < a[i-1]) return false;
return true;
}
// generate N real numbers between 0 and 1, and mergesort them
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
double[] a = new double[N];
for (int i = 0; i < N; i++)
a[i] = (int)(Math.random() * 100 + 1);
a = mergesort(a);
for (int i = 0; i < N; i++)
StdOut.println(a[i]);
StdOut.println(isSorted(a));
}
}
答案 0 :(得分:1)
只需使用循环:
for (int i = 0; i<array.length;i++){
System.out.print(array[i]);
if (i%10 == 9) { // if i modulo 10 is 9 add an linebreak
System.out.println();
}
}
答案 1 :(得分:0)
使用System.out.print()
代替System.out.println()
。
System.out.println()
会自动添加&#34; \ n&#34;在System.out.print()
获胜的情况下,在你的行尾。