我希望能够看到气泡排序对数组中的所有元素进行排序所需的时间。如何测量时间?
public class Bubble {
static int[] nums = {5, 4, 3, 2, 1};
public static void main(String[] args) {
bubble(nums);
for(int i=0; i<nums.length; i++){
System.out.print(nums[i] + " ");
}
}
// bubble sort
public static void bubble(int[] unsorted){
int temp;
boolean sorted = false;
int length = unsorted.length;
while(!sorted){
sorted = true;
for(int i=0; i<length-1; i++){
if(unsorted[i] > unsorted[i+1]){
temp = unsorted[i];
unsorted[i] = unsorted[i+1];
unsorted[i+1] = temp;
sorted = false;
}
}
}
}
}
最佳答案
从灾难主义对how do I time a methods excecution in java的回答:
总有一种老式的方式:
long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();
long duration = endTime - startTime;