Search code examples
javabubble-sort

I need to time a bubbleSort function, which stops if a certain time limit is reached. How do i do that in java?


public static long[] bubbleSort(String[] array, long limit) {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j].compareTo(array[j + 1]) > 0) {
                    String temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
                if ( System.currentTimeMillis() - startTime > limit * 10) {
                    return new long[] {0L, System.currentTimeMillis() - startTime};
                }
            }
        }
        return new long[] {1L, System.currentTimeMillis() - startTime};
    }

This is the code I wrote. And its not good. This function takes too much time. But if I remove the if block

if ( System.currentTimeMillis() - startTime > limit * 10) {
        return new long[] {0L, System.currentTimeMillis() - startTime};
}

its a lot faster! for example: with the if block, time is = Sorting time: 0 min. 0 sec. 81 ms. without the if block = Sorting time: 0 min. 0 sec. 15 ms. if the limit is = 4ms., then the function will always return without running its full course.

why is this happening? what else can i do?

P.S.: return array's first value is used to check if sort was completed or not.


Solution

  • First of all, to optimize performance what we can try is to move the comparison,

    if ( System.currentTimeMillis() - startTime > limit * 10) {
        return new long[] {0L, System.currentTimeMillis() - startTime};
    }
    

    to the outer loop, from the nested loop. This provides lots of improvement, if the size of your array, is sufficiently large.

    A better way to do it is to use Timer class, or multithreading, as explained in the following posts:

    Setting Timeout in Java

    How to set a Timer in Java