I try below program to check if same algorithm runs few times on same array will it give different time durations for sorting.It returned different times. Why is that ? i used same array for all attempts. package sorting;
import java.util.Arrays;
import static sorting.CompareSorting.bubble_sort;
import static sorting.CompareSorting.generate_data;
public class Sorting {
public static void main(String [] args){
int size = 10000;
int [] arr = new int[size];
int [] arr1 = new int[size];
int [] arr2 = new int[size];
long startTime;
long endTime;
arr = generate_data(size);
System.arraycopy(arr, 0, arr1, 0, size);
System.arraycopy(arr, 0, arr2, 0, size);
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
startTime = System.currentTimeMillis();
bubble_sort(arr);
endTime = System.currentTimeMillis();
System.out.println("1st attempt " + (endTime - startTime));
startTime = System.currentTimeMillis();
bubble_sort(arr1);
endTime = System.currentTimeMillis();
System.out.println("2nd attempt " + (endTime - startTime));
startTime = System.currentTimeMillis();
bubble_sort(arr2);
endTime = System.currentTimeMillis();
System.out.println("3rd attempt " + (endTime - startTime));
}
}
This is the sorting method
static void bubble_sort(int [] data) {
int i,j,tmp;
for(i = data.length ; i >= 0 ; i-- ){
for(j = 0 ; j < data.length - 1 ; j++ ){
if(data[j] > data[j + 1]){
tmp = data[j];
data[j] = data[j + 1];
data[j + 1] = tmp;
}
}
}
}
Returned values : 1st attempt 438 2nd attempt 359 3rd attempt 297