3

公共类排序{

public static void main(String[] args) {

    int[] random = { 8, 32, 26, 1870, 3, 80, 46, 37 };
    int[] decreasing = { 1870, 80, 46, 37, 32, 26, 8, 3 };
    int[] increasing = { 3, 8, 26, 32, 37, 46, 80, 1870 };

    System.out.println("|\t\t| random  |decreasing|increasing|");
    System.out.println("|---------------|-----------|-----------|----------|");
    System.out.println("|Bubblesort\t| " + bubbleSort(random) + " ms\t|" + bubbleSort(decreasing) + " ms\t|"
            + bubbleSort(increasing) + " ms\t|");
    }

public static long bubbleSort(int[] arr) {

    long start = System.currentTimeMillis();

    for (int j = 0; j < arr.length - 1; j++) {
        for (int i = 0; i < arr.length - j - 1; i++) {
            if (arr[i + 1] < arr[i]) {
                arr[i + 1] = arr[i] + arr[i + 1];
                arr[i] = arr[i + 1] - arr[i];
                arr[i + 1] = arr[i + 1] - arr[i];
            }
        }
    }

    return System.currentTimeMillis() - start;

}

}

输出:

在此处输入图像描述

我写了一个程序,它执行 bubbleSort 方法并返回它所花费的时间,以 ms 为单位。我想打印返回值,但我得到所有数组的 0。当我调试程序时,我可以看到它返回了一些其他数字。但是当涉及到打印时,它的打印为 0。我不明白这个问题。有人可以帮帮我吗?

4

1 回答 1

2

尝试使用System.nanoTime()代替System.currentTimeMillis(). nanoTime 函数使用纳秒作为单位,而不是毫秒,这使得程序运行时不太可能没有时间流逝。

但是,实际上您需要测试更长的数组——尝试数千或数万个元素。您不会通过对如此短的数组进行排序获得真正有用​​的时序数据。您可能想要编写代码来生成包含许多随机元素的数组,然后使用内置方法(例如Arrays.sort)将随机数据排序到递减或递增的测试列表中。

如果我想举行一场比赛以确定谁是跑得最快的,并且我设置了一条长一厘米(或一英寸)的路线,我能否从结果中确定任何有用的信息?可能不是。但是,如果课程是 100 米、400 米或 5 公里,那么我将能够从结果中学到一些有用的东西。

于 2021-01-14T21:45:28.843 回答