【问题标题】:Bubble Sorting an Array of random values of 1-100对 1-100 的随机值数组进行冒泡排序
【发布时间】:2014-04-01 15:57:30
【问题描述】:

这是作业 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;
            }
        }
    }
}

【问题讨论】:

  • 查看Random类。
  • 如@ZouZou所说,使用Random类为你生成100个随机值。
  • 欢迎来到 SO。开发人员(或任何人,真的)可以拥有的最重要的技能是了解如何在 Google 上查找内容。如果您在 Google 中输入“java random”,您将获得数千次点击,第一页上有大量有用的信息。

标签: java random bubble-sort


【解决方案1】:

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

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

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

您应该查看Random 的文档。

【讨论】:

    【解决方案2】:

    我会附和 Jim 在 cmets 中所说的话。足智多谋是软件开发人员的一项重要技能。谷歌搜索会很快找到一篇有用的文章,比如this one

    您需要使用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(包括)和指定整数(不包括)之间的伪随机整数。这就是将1 添加到nextInt(100) 的输出的原因,因为它会根据需要将您的输出范围从0-99 转移到1-100

    【讨论】:

      【解决方案3】:
      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)
         }
      }
      

      【讨论】:

      • @Dylan:这不会产生1-100的指定范围。实际上,nextInt(int start, int end) 甚至不是Random 类的有效方法。
      • 糟糕,混合语言时会发生这种情况:P
      • 还没有。看我的回答。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 2020-08-12
      • 2011-12-06
      • 1970-01-01
      • 2020-05-17
      相关资源
      最近更新 更多