[英]Bubble Sorting an Array of random values of 1-100
This was assignment 1.这是作业 1。
Now I have to create the same thing but use a random array of 1-100 values and i have no clue how implement that into what i already have.现在我必须创建相同的东西,但使用 1-100 个值的随机数组,我不知道如何将它实现到我已经拥有的东西中。
public class Test {
public static void main(String a[]) {
int i;
int[] array = {9,1,5,8,7,2,1,5,5,6,8,15,3,9,19,18,88,10,1,100,4,8};
System.out.println("Values Before the sort:\n");
for (i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
bubble_srt(array, array.length);
System.out.print("Values after the sort:\n");
for (i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
}
public static void bubble_srt(int a[], int n) {
int i, j, t = 0;
for (i = 0; i < n; i++) {
for (j = 1; j < (n - i); j++) {
if (a[j - 1] > a[j]) {
t = a[j - 1];
a[j - 1] = a[j];
a[j] = t;
}
}
}
}
You need to use a random generator to get the numbers.您需要使用随机生成器来获取数字。 For an array of size X it would be something like this:对于大小为 X 的数组,它将是这样的:
int[] array = new int[X];
Random random = new Random();
for (int i = 0; i < X; i++)
array[i] = random.nextInt(100) + 1;
You should take a look at the documentation for Random .您应该查看Random的文档。
public void generateRandom()
{
int[] x = new int[100]; // This initializes an array of length 100
Random rand = new Random();
for(int i = 0; i < 100; i++)
{
x[i] = rand.nextInt(100); // Use the random class to generate random integers (and give boundaries)
}
}
I'll echo what Jim has said in the comments.我会回应吉姆在评论中所说的话。 Being resourceful is an important skill as a software developer.足智多谋是软件开发人员的一项重要技能。 A Google search would have quickly turned up a helpful article like this one .谷歌搜索会很快变成像一个有用的文章这一个。
You need to use the Random
class to accomplish this.您需要使用Random
类来完成此操作。
Random randomGenerator = new Random();
int array = new int[100];
for (int idx = 0; idx < 100; ++idx){
array[idx] = randomGenerator.nextInt(100) + 1;
}
Note on the usage of the nextInt(int n) method:注意nextInt(int n)方法的使用:
It produces a pseudo-random integer between 0 (inclusive) and the specified integer (exclusive).它产生一个介于 0(含)和指定整数(不含)之间的伪随机整数。 That is the reason for adding 1
to the output of nextInt(100)
as it shifts your output range from 0-99
to 1-100
as desired.这就是将nextInt(100)
的输出加1
的原因,因为它会根据需要将您的输出范围从0-99
到1-100
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.