您好我现在正在尝试编写冒泡排序实现。然后我发现如果我重新初始化数组然后再次排序这个数组,排序的时间比第一次小得多。这是我的代码:
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
}
}
}
对第一个数组进行排序的时间是13毫秒,而对第二个数组进行排序的时间是5毫秒。但实际上我们应该得到类似的结果......但是我的结果绕道而且每次排序第二个数组的时间都比第一个数组要小得多。我很困惑......