【发布时间】: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,尤其是
SummaryStatistics和DescriptiveStatisticscommons.apache.org/proper/commons-math/userguide/stat.html
标签: java arrays algorithm sorting average