I want to be able to see how long it took for a bubble sort to sort all the element in the array. How do I measure the time?
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;
}
}
}
}
}
From Diastrophism's answer to how do I time a methods excecution in java:
There is always the old-fashioned way:
long startTime = System.nanoTime(); methodToTime(); long endTime = System.nanoTime(); long duration = endTime - startTime;