如何将此数组升序排序?

时间:2018-10-20 17:22:25

标签: java sorting arraylist

我想生成一个由100个数字组成的数组,并求出它们的平均值和总和。我能够做到这一点,但是我无法使数字的输出升序。我是Java的新手。

import java.util.Random;

public class randomNumberGen
{
    public static void main(String [] args)
    {
        Random r=new Random();
        double sum = 0; // is double so to prevent int division later on
        int amount = 100;
        int upperBound = 100;

        for (int i = 0; i < amount; i++){
             int next = r.nextInt(upperBound) + 1; // creates a random int in [1,100]
            System.out.println(next);

            sum += next; // accumulate sum of all random numbers
        }

        System.out.println("Your average is: " + (sum / amount));
        System.out.println("Your sum is: " + (sum));        
    }
}

3 个答案:

答案 0 :(得分:1)

这很容易。但是我没有在您的代码中看到任何数组。我为您创建了示例代码。您可以寻求更多帮助。

public static void main(String[] args) {
    SecureRandom random = new SecureRandom(); // it is better to use this library
    double sum = 0; // is double so to prevent int division later on
    int amount = 100;
    int upperBound = 100;
    int[] array = new int[amount]; // create an array with amount size
    for (int i = 0; i < amount; i++) {
        array[i] = random.nextInt(upperBound) + 1; // creates a random int in [1 , upperBound]
        sum += array[i]; // accumulate sum of all random numbers
    }
    Arrays.sort(array); // sort array in default order which is ascending
    System.out.println(Arrays.toString(array)); // toString is a way to print all of array, without iterate it and print it
    System.out.println("Your average is: " + (sum / amount));
    System.out.println("Your sum is: " + sum);
}

答案 1 :(得分:0)

有很多不同的排序方法。对于初学者,请从Bubble SortInsertion Sort开始。插入排序稍好一些,因为平均而言运行速度稍快一些。

答案 2 :(得分:0)

我提供使用一种特殊的集合在内部对数字进行排序,而无需使用一种排序算法(例如我们PriorityQueue):

public static void main(String[] args) {
    final int amount = 100;

    Random random = new SecureRandom();
    Queue<Integer> queue = new PriorityQueue<>(amount, Comparator.naturalOrder());  // Comparator.reverseOrder() for reverse order
    int sum = 0;

    for (int i = 0; i < amount; i++) {
        int val = random.nextInt(100) + 1;
        sum += val;
        queue.add(val);
    }

    System.out.println(Arrays.toString(queue.toArray()));
    System.out.println("Your average is: " + (double)sum / amount);
    System.out.println("Your sum is: " + sum);
}