我寫了一個冒泡排序程序,可以將10000個唯一值按順序排序。JAVA BubbleSort運行時間故障
我已經運行該程序,它給了我一個輸出,但輸出似乎並沒有看起來對我。
下面是代碼:
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毫秒運行整個程序,和我不要認爲輸出結果正是我想要做的,儘管它看起來像。我希望輸出程序運行的時間以及每個排序時間。
〜我希望這是有道理的。 任何幫助,將不勝感激,謝謝。
您只對數組排序一次,但是您輸出數組的每個元素所用的時間相同。那是你想要做的嗎? – 2012-12-06 08:49:08
是的,這是正確的。我希望對數組進行排序,並顯示數組排序所花費的總時間(使用nanoTime函數)。 –