1

I am doing project on efficiency of sorting algorithm. Lets say I performed 50 iterations of bubble sorts and find the average time taken for n numbers. But I realize that the first few iterations are always slower than subsequent iterations

e.g. 1394ms, 1381ms, 1001ms, 1008ms, 1008ms ,1011ms...

        long lStartTime = System.currentTimeMillis();
        bubbleSort(R); // R is the array of int
        long lEndTime = System.currentTimeMillis();
        long difference = lEndTime - lStartTime;

What could be the reason behind it? It is because cpu able to tell which set of data to be stored into cache? If so, should I not use the subsequent computing time for analysis as it is not realistic?

Thanks!

edit: im doing other sorting algorithms too, bubble sort as an example but the thing is it happens to all of the sorts i did except for insertion

public static int[] bubbleSort(int[] S) {
    int counter = 0;
    boolean isUnsort = true;
    while (isUnsort) {
        isUnsort = false;

        for (int i = 0; i < S.length - 1 - counter; i++) {
            if (S[i] > S[i + 1]) {
                int temp = S[i];
                S[i] = S[i + 1];
                S[i + 1] = temp;
                isUnsort = true;
            }

        }
        counter++;
    }
    return S;
}
Ren Fa Kay
  • 107
  • 1
  • 9
  • how does your implementation of bubble sort look like? Bubble sort can give efficiency between O(R) to O(R2) – Nikhil Talreja Jul 16 '14 at 05:48
  • 1
    It could be due to the JIT compilation in Java that causing such scenario. [JIT](http://en.wikipedia.org/wiki/Just-in-time_compilation). However, is your array data, R a constant ? Different input could produce different sorting time. – bLaXjack Jul 16 '14 at 05:51
  • added the bubble sort codes. R size is constant, the data are generated with Math.random(). but it is always the first few iteration that is slower than the subsequent ones so i doubt it is due to the input – Ren Fa Kay Jul 16 '14 at 05:59
  • 1
    @RenFaKay JIT should be the reason why the first few iteration is taking longer input. Suggest to filter them out for calculation. As the input is random, the calculation time could be varry as well. – bLaXjack Jul 16 '14 at 06:07

1 Answers1

4

It's probably the Just-in Time Compiler translating your byte-code into a more efficient form. I suggest you run at least one (but preferably a few) warm-up sort(s) before you begin your timer. Also, bubble sort is a horribly inefficient sort.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249