我写了一个冒泡排序程序,按顺序对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毫秒在整个程序中运行,我不认为输出正是我正在尝试做的,尽管它看起来像。我希望输出程序运行所需的时间以及每个排序时间。
〜我希望这是有道理的。 任何帮助将不胜感激,谢谢。
答案 0 :(得分:1)
我想你可能想输出这个。 sysout
应该在for
循环之前。
System.out.println(“排序时间:”+ timeTaken +“毫秒。”); for(int a = 0; a&lt; 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;
}
}
所以,那就是总时间。