0

我编写了一个冒泡排序程序,将 10000 个唯一值按顺序排序。

我已经运行了该程序,它给了我一个输出,但输出对我来说似乎不正确。

这是代码:

public class BubbleSort {
    public static void main(String[] args) {
        int BubArray[] = new int[]{#here are 10000 integers#};
        System.out.println("Array Before Bubble Sort");
            for(int a = 0; a < BubArray.length; a++){
                 System.out.print(BubArray[a] + " ");
            }

            double timeTaken = bubbleSortTimeTaken(BubArray);
                 bubbleSort(BubArray);
            System.out.println("");               
            System.out.println("Array After Bubble Sort");
            for(int a = 0; a < BubArray.length; a++){
        System.out.println("    Time taken for Sort : " + timeTaken + " milliseconds.");
                System.out.print(BubArray[a] + " ");
            }
    }

private static void bubbleSort(int[] BubArray) {

            int z = BubArray.length;
            int temp = 0;

            for(int a = 0; a < z; a++){
                    for(int x=1; x < (z-a); x++){

                            if(BubArray[x-1] > BubArray[x]){

                                    temp = BubArray[x-1];
                                    BubArray[x-1] = BubArray[x];
                                    BubArray[x] = temp;

                            }      
                    }
            }
    }
public static double bubbleSortTimeTaken(int[] BubArray) {
    long startTime = System.nanoTime();
        bubbleSort(BubArray);
    long timeTaken = System.nanoTime() - startTime;
    return timeTaken;
    }
}

代码运行顺利,没有错误,但这是我收到的输出:

Array Before Bubble Sort
#10000 integers randomly#
Array After Bubble Sort
Time taken for Sort : 1.0114869E7 milliseconds.
10  Time taken for Sort : 1.0114869E7 milliseconds.
11  Time taken for Sort : 1.0114869E7 milliseconds.
17  Time taken for Sort : 1.0114869E7 milliseconds.
24  Time taken for Sort : 1.0114869E7 milliseconds.
35  Time taken for Sort : 1.0114869E7 milliseconds.
53  Time taken for Sort : 1.0114869E7 milliseconds.

....

14940   Time taken for Sort : 1.0114869E7 milliseconds.
14952   Time taken for Sort : 1.0114869E7 milliseconds.
14957   Time taken for Sort : 1.0114869E7 milliseconds.
14958   Time taken for Sort : 1.0114869E7 milliseconds.
14994   Time taken for Sort : 1.0114869E7 milliseconds.
14997   Time taken for Sort : 1.0114869E7 milliseconds.
BUILD SUCCESSFUL (total time: 1 second)

1.0114869E7 毫秒在整个程序中运行,我不认为输出正是我想要做的,尽管它看起来像。我希望输出程序运行所需的时间以及每次排序时间。

~我希望这是有道理的。任何帮助将不胜感激,谢谢。

4

1 回答 1

1

我猜你可能想输出这个。sysout应该在循环for之前。

System.out.println(" 排序所用时间:" + timeTaken + " 毫秒。"); for(int a = 0; a < BubArray.length; a++){ System.out.print(BubArray[a] + " "); }

您已经对数组进行了排序,稍后将在 for 循环中显示它。您看到输出的时间是冒泡排序所花费的总时间(大约),这是通过以下方法计算的

public static double bubbleSortTimeTaken(int[] BubArray) {
    long startTime = System.nanoTime();
    bubbleSort(BubArray);
    long timeTaken = System.nanoTime() - startTime;
    return timeTaken;
    }
}

所以,这就是总时间。

于 2012-12-06T08:48:55.043 回答