gpt4 book ai didi

java - [处理2.0]尝试创建一个随机整数数组,然后对它们进行冒泡排序

转载 作者:行者123 更新时间:2023-12-01 13:48:53 25 4
gpt4 key购买 nike

我试图在处理中提出一个随机整数数组,然后使用冒泡排序对它们进行排序,但我想先打印未排序的随机整数列表,然后排序并打印,我也希望该数组是(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();
}

最佳答案

首先,为什么要为随机数创建单独的值。你应该做这样的事情:

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]);
}

然后进行冒泡排序,然后再次调用上面的代码以按顺序打印它们。

关于java - [处理2.0]尝试创建一个随机整数数组,然后对它们进行冒泡排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20128677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com