Hi I am now trying to write bubble sort implementation. Then I find that if I reinitialize the array then sort this array again, the time to sort is much smaller than the first time. Here is my code:
import java.util.Random;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
long start;
long end;
int [] array = new int [1000];
initializeArray(array);
start = System.currentTimeMillis();
bubble_srt(array);
end = System.currentTimeMillis();
System.out.println("To sort the array using bubble sort, we need " + (end - start) + " ms");
initializeArray(array);
start = System.currentTimeMillis();
bubble_srt(array);
end = System.currentTimeMillis();
System.out.println("To sort the array using bubble sort, we need " + (end - start) + " ms");
}
public static void bubble_srt(int array[]) {
int n = array.length;
int k;
for (int m = n; m >= 0; m--) { //starts from the rightmost position in arrayy
for (int i = 0; i < n - 1; i++) { //starts from the leftmost position in array
k = i + 1;
if (array[i] > array[k]) {
swapNumbers(i, k, array); //choose a bigger one to the i+1 position
}
}
}
}
private static void swapNumbers(int i, int j, int[] array) {
int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void initializeArray(int array[]){
Random ran = new Random();
for(int i = 0; i < array.length; i++){
array[i] = -ran.nextInt(10001) + 5000; // create a random number rangre from -5000 - 5000
}
}
}
The time to sort the first array is 13ms, while to sort the second array is 5ms. But in fact we should get the similar result... But my result detour and every time the time to sort the second array is much smaller than the first array. I am quite confused about it...