【问题标题】:Finding Min/Max/Avg When Benchmarking Sorting Algorithms - Java在对排序算法进行基准测试时查找最小值/最大值/平均值 - Java
【发布时间】:2014-04-10 19:51:55
【问题描述】:

在下面包含的主要方法中,我运行冒泡排序来对包含 10,000 个随机项的数组进行排序。我使用 for 循环对该数组进行排序总共 100 次。然后,我输出系统对这个由 10,000 个整数组成的随机集合进行排序所花费的总时间。

我不想输出 100 个不同的经过排序时间,而是从这组 100 个经过时间中简单地输出三个数字: 1) 使用冒泡排序对 10,000 个随机整数进行排序所需的平均时间(只是输出的平均值) 2) 对 10,000 个随机整数进行排序所需的最短时间。 3) 对 10,000 个随机整数进行排序所花费的最长时间。

任何帮助将不胜感激。

这是我使用的主要方法:

public static void main(String[] args) {

    //run sorting algorithm a total of 100 times
    for (int k = 1; k<= 100; k++){
        int dataSz = 10000; //size of data set to be sorted
        int[] a = new int[dataSz]; //create array with dataSz new items
        int[] temp = new int [a.length]; //create empty temporary array with
        //same number of items as above array

        //fill the array with random integers
        for (int i=0; i<a.length; i++)
            a[i] = (int) (Math.random()*100000+1);

        //get the start time in nanoseconds
        long startTime = System.nanoTime();

        //run Bubble Sort to sort the entire array
        bubbleSort(a);

        //get the end time in nanoseconds
        long endTime = System.nanoTime();

        //calculate elapsed time in nanoseconds
        long duration = endTime - startTime;

        //print the elapsed time in seconds (nanoseconds/1 billion)
        System.out.printf("%12.8f %n", (double)duration/100000000);

这是我运行程序后系统输出的内容。 注意 我希望我的 avg、min 和 max 遵循与当前系统输出相同的语法。谢谢。

run:
1.77562000 
1.54235000 
1.26343000
... continues for 100 
... total
... sorting durations
1.26230000 
1.26011000 
1.26398000 
BUILD SUCCESSFUL (total time: 13 seconds)

【问题讨论】:

  • 您是否尝试将运行时间添加到TreeSet
  • @ProgrammerDan 不,我以前从未使用过 TreeSet。我会查找它们,看看它们是否对我的计划有帮助。
  • 你不需要存储每个运行时,你可以只计算一个moving average
  • @ProgrammerDan 您如何将运行时间添加到 TreeSet?
  • 考虑使用 Apache Commons Math,尤其是 SummaryStatisticsDescriptiveStatistics commons.apache.org/proper/commons-math/userguide/stat.html

标签: java arrays algorithm sorting average


【解决方案1】:

计算最小值和最大值非常简单——只需使用两个辅助变量,一个用于最小值,一个用于最大值,并在每次新测量时更新它们。

计算平均值只是稍微困难一点——你需要辅助变量,但这次你需要两个。计算您在第一个中完成的测量次数,并将累积的时间存储在第二个中。然后计算平均值就是简单地将累积时间除以测量次数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 2016-11-04
    • 2012-10-13
    • 2020-06-17
    • 2016-12-29
    相关资源
    最近更新 更多