我试图在处理中提出一个随机整数数组,然后使用冒泡排序对它们进行排序,但我想首先打印未排序的随机整数列表然后排序和打印,我也希望数组是(1-100)之间。这是我写的尝试这个的代码,但我想我可能会离开。谢谢你的回复。
int[] arr = new int[10];
int min = 1;
int max = 100;
int Random = int(random(min, max));
int R0 = int(random(min, max));
int R1 = int(random(min, max));
int R2 = int(random(min, max));
int R3 = int(random(min, max));
int R4 = int(random(min, max));
int R5 = int(random(min, max));
int R6 = int(random(min, max));
int R7 = int(random(min, max));
int R8 = int(random(min, max));
int R9 = int(random(min, max));
println ("The Length of the Array is: " + arr.length);
println ("The " + arr.length + " random numbers chosen between (" + min + " - " + max + ") are: " + R0 + ", " + R1 + ", " + R2 + ", " + R3 + ", " + R4 + ", " + R5+ ", " + R6 + ", " + R7 + ", " + R8 + ", " + R9 + ".");
for (int i = 0; i <100; i++)
{ print((arr[i]= Random + i ) + ", ");
}
编辑:我提出的最终修订版本:
int Random = int(random(10, 100));
int[] array = new int[Random]; // RANDOM SIZE OF ARRAY
int min = 10; // MINIMUM RANDOM INTEGER CHOSEN
int max = 100; // MAX RANDOM INTEGER CHOSEN
int temp;
for (int i=0; i<array.length; i++) {
array[i] = (int)random(min,max);
}
println("The Amount of Numbers That Will Be Chosen Is: " + array.length);
println("The Unsorted Numbers Chosen Are Between (" + min + " - " + max + ").");
println();
println("The Numbers Are:");
println(array);
println();
println("The Sorting Begins");
for (int i = 0; i < array.length; i++)
{
println();
println("Step " + i); // Prints the step of insertion using "i" as the counter
for (int j = 0; j < i; j++)
{
print(array[j] + ", ");
if (array[i] < array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
println();
}
答案 0 :(得分:1)
首先,为什么要为您的randoms创建单独的值。你应该做这样的事情:
int[] iArr = new int[50];
for (int i=0; i<iArr.length; i++) {
iArr[i] = (int)random(min,max);
}
这将创建一个50的数组,并使用上面的代码用随机数填充它。
接下来你需要打印未分类的:
System.out.println("Unsorted:");
for(int i=0; i<iArr.length; i++) {
System.out.println(iArr[i]);
}
然后进行冒泡排序,然后再次调用上面按顺序打印它们。
答案 1 :(得分:0)
我也希望数组介于(1-100)
之间
提示:使用Random
类,它提供了一个很好的函数nextInt(int n)
函数:返回伪随机,在0
(包含)之间均匀分布的int值指定值n
(独占),从此随机数生成器的序列中提取。