繁体   English   中英

对 1-100 的随机值数组进行冒泡排序

[英]Bubble Sorting an Array of random values of 1-100

这是作业 1。

现在我必须创建相同的东西,但使用 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;
            }
        }
    }
}

您需要使用随机生成器来获取数字。 对于大小为 X 的数组,它将是这样的:

int[] array = new int[X];
Random random = new Random();

for (int i = 0; i < X; i++)
    array[i] = random.nextInt(100) + 1;

您应该查看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)
   }
}

我会回应吉姆在评论中所说的话。 足智多谋是软件开发人员的一项重要技能。 谷歌搜索会很快变成像一个有用的文章这一个

您需要使用Random类来完成此操作。

Random randomGenerator = new Random();
int array = new int[100];
for (int idx = 0; idx < 100; ++idx){
  array[idx] = randomGenerator.nextInt(100) + 1;
}

注意nextInt(int n)方法的使用:

它产生一个介于 0(含)和指定整数(不含)之间的伪随机整数。 这就是将nextInt(100)的输出加1的原因,因为它会根据需要将您的输出范围从0-991-100

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM