[英]Why does this sorting algorithm with smaller time complexity takes longer time?(Edited)
我寫了兩個最簡單的排序算法,它們幾乎一樣,但是一個要執行一半以上的操作需要兩倍的時間。 我無法理解為什么會發生這種情況。
任何指針都將不勝感激,因為我試圖了解最有效的排序方式,考慮到不同的情況,一種簡單的排序讓我感到困惑。
public class Sort{
static long timerStart;
static long timerEnd;
static long passedTime;
public static void main(String[] args) {
double[] arr = createDoubleArray(10000);
double[] arr2 = Arrays.copyOf(arr,arr.length);
startTimer();
sortDoubleArrayFast(arr);
stopTimer();
computationTime();
startTimer();
sortDoubleArraySlow(arr2);
stopTimer();
computationTime();
}
public static void startTimer(){
timerStart = System.currentTimeMillis();
}
public static void stopTimer(){
timerEnd = System.currentTimeMillis();
}
public static void computationTime(){
passedTime = timerEnd-timerStart;
System.out.println("The operations took: " +passedTime+"ms");
}
public static double[] createDoubleArray(int size){
double[] output = new double[size];
for (int i = 0; i < size; i++) {
output[i] = Math.random()*10000000;
}
return output;
}
public static double[] sortDoubleArraySlow(double[] input){
double tmp;
int operationNumber = 0;
for (int j = 0; j < input.length; j++) {
for (int i = 0; i < input.length; i++) {
operationNumber++;
if(input[i]>input[j]){
tmp = input[j];
input[j] = input[i];
input[i] = tmp;
}
}
}
System.out.println("Operation number in Slow: "+operationNumber);
return input;
}
public static double[] sortDoubleArrayFast(double[] input){
double tmp;
int operationNumber = 0;
for (int j = 0; j < input.length-1; j++) {
for (int i = j+1; i < input.length; i++) {
operationNumber++;
if(input[i]>input[j]){
tmp = input[j];
input[j] = input[i];
input[i] = tmp;
}
}
}
System.out.println("Operation number in Fast: "+operationNumber);
return input;
}
}
我很驚訝這個問題被否決了,因為正如您從評論中看到的那樣,答案並不明顯。 您的問題的答案“相對”簡單 - JIT。 當我們有一個每次都做完全相同的事情的循環時,JIT 將其轉換為一段本機代碼並直接執行。 但是,當我們每次執行改變內循環時(改變開始 i = j + 1),那么 JIT 就不起作用了,所以 JVM 必須重新解釋它,這已經造成了時間開銷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.