Search code examples
javabubble-sort

I get different running times for bubblesort in Java


I have created a new bubble sort project and i want to know how much time it takes. Hence, I have added a getTime() method, which returns nanotime. I have also created an array with 9 static values. When I run my code i get different running times (ie: generally i get 3849 ns but sometimes 6432 or 4277 ns). How can this be?

My code is as follows:

long time2;
public void sort(int[] dizi){
    long time = System.nanoTime();
    for (int i = dizi.length-1; i >0; i--) {
        for (int j = 0; j < i; j++) {
            if(dizi[j]>dizi[j+1]){
                super.swap(dizi, j, j+1);
            }
        }
    }
    time2 = System.nanoTime() - time;
}
public long getTime(long time){
      return time;
}
main(){
      BubbleSort bubbleSort = new BubbleSort();
      int[] arr = {4,2,1,8,9,5,3,7,6};
      bubbleSort.sort(arr);
      Sysout(bubbleSort.getTime(time2));
}

Solution

  • There are multiple factors that may affect the result.

    JVM may start running garbage collection (that's definitely not your case), while running your program JVM may allocate some memory and the underlying OS service finds out that it should swap some memory, because it has run out of available RAM, etc...

    None of available JVMs (for Mac, Windows and Linux/Unix) runs on a real time system, but even if one day it does - your JVM may decide that your program has lower priority compared to some JVM activity.

    Try some lager array, the results will be more stable.