[英]Finding Min/Max/Avg When Benchmarking Sorting Algorithms - Java
在下面包含的主要方法中,我运行冒泡排序来对包含 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)
计算最小值和最大值非常简单 - 只需使用两个辅助变量,一个用于最小值,一个用于最大值,并在每次测量时更新它们。
计算平均值只是稍微困难一点——你需要辅助变量,但这次你需要两个。 计算您在第一次完成的测量次数,并将累计时间存储在第二次中。 然后计算平均值很简单——将累积时间除以测量次数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.