使用随机数和数组的排序方法的时间测试问题 [英] Time testing problem for sorting methods using random numbers and arrays

查看:35
本文介绍了使用随机数和数组的排序方法的时间测试问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最后有带有时间分析代码的排序方法的工作代码,但无法弄清楚排序方法的随机数或数组生成器代码放在哪里.每次尝试时都会出错,希望有人可以告诉我调用随机方法而不是默认分配时的外观.另外,计时部分做对了吗?似乎不需要那么长时间,当我运行时,我得到类似 69391841667800 纳秒的信息.

I have working code for sort methods with time analysis code in the end, but can't figure out where to put the random number or array generator code for the sort methods. I get errors each time I try, hopefully someone can show me how it looks when the random method is called instead of the default assign. Also, is the timing part done right? It doesn't seem like it should take that long, when I run I get something like 69391841667800 nanoseconds.

public class InsertSort {
private int[] arr;
public InsertSort(int[] array) {
arr = array;
}
private boolean more(int value1, int value2)
{
return value1 > value2;
}
public void sort()
{
int size = arr.length;
int temp,j;
for(int i=1; i<size; i++)
{temp=arr[i];
for(j=i; j>0 && more(arr[j-1], temp); j--)
{
arr[j]=arr[j-1];
}
arr[j]=temp;
}
}
public static void main(String[] args)
{
int[] array = {9,1,8,2,7,3,6,4,5};
InsertSort bs = new InsertSort(array);
bs.sort();
for(int i=0;i<array.length ;i++)
{
System.out.print(array[i] + " ");
}
long endTime = System.nanoTime(); //Current system Time at end

long startTime = 0;
long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.

System.out.print(duration);
}
}

这是我的随机数生成器代码

This is my code for random number generator

import java.util.ArrayList;

public class Random {

public static void main(String[] args)
{
    System.out.println(generateRandomList(5, 1, 10));
}

public static ArrayList<Integer> generateRandomList( int size, int min, int max) {
    ArrayList<Integer> list;
    list = new ArrayList<>();
    for(int i=0;i<size;i++) {
        int n = (int)(Math.random() * (max-min))+min;
        list.add(n);
    }
    return list;
}

}

推荐答案

你需要更换

int[] array = {9,1,8,2,7,3,6,4,5};

在你的第一个主方法中调用 generateRandomList 像这样

in your first main method with call to generateRandomList like this

int[] array = Random.generateRandomList(5, 1, 10);

如果您不使用 IDE,则可能需要添加 Random 类以导入主类的部分.

If you are not using IDE you may need tonadd you Random class to import section of your main class.

并且测量 Java 代码的执行时间非常非常重要.请查看以下链接以获取更多信息 https://www.baeldung.com/java-microbenchmark-线束

And measuring execution time for java code is very non-trivial. Please check the following link for more information https://www.baeldung.com/java-microbenchmark-harness

这篇关于使用随机数和数组的排序方法的时间测试问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆