1

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;
                }
            }
        }
    }
}

5 Answers5

0

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;
Community
  • 1
  • 1
0x6C38
  • 6,796
  • 4
  • 35
  • 47
0

See this How do I time a method's execution in Java? Basically get the time at the beginning and then the time at the end and subtract.

Community
  • 1
  • 1
Jias
  • 164
  • 12
0

Right before you call:

bubble(nums);

use:

long time = System.nanoTime();

to obtain the current system time in nanoseconds before the sort. Then right after the sort is done, use:

time =- System.nanoTime();

If you divide this by 1000000000.0f, you will have the time in seconds. However, since your array is likely not large enough, you can display the nanoseconds instead because dividing by 1000000000.0f might result in it being rounded off to 0.

huu
  • 7,032
  • 2
  • 34
  • 49
0

You can use this code :

public static void main(String[] args) {
    long t1 = System.nanoTime();
    bubble(nums);
    for(int i=0; i<nums.length; i++){
        System.out.print(nums[i] + " ");
    }
    long t = (System.nanoTime() - t1) / 1000000;
    System.out.println("Elapsed time = " + t + " ms");

}

It will display 0ms. It is because your array is far too small. Try with a lot more items. Complexity is O(n²).

EDIT: You can use nanoTime without dividing, but our computer are not capable to measure time shorter than 1ms. So the measure is incorrect. Better to measure with more elements 1000, 2000, 3000 etc

mki
  • 635
  • 3
  • 10
0
public static void main(String[] args) {
   Date startTime = new Date();
   bubble(nums);
   System.out.println(new Date().getTime() - startTime.getTime());
   for(int i=0; i<nums.length; i++){
       System.out.print(nums[i] + " ");
   }
}
lars-august
  • 378
  • 2
  • 9