[英]Value changes but is only used as parameter
我必須用PHP從Java重新編寫實現vor插入/選擇排序。 因此,算法可以正常工作,但是在編寫快速程序時為了使用多類型值而使用Logger類時,在后面處理所有不同類型的工作很麻煩。
由於我已經有一段時間沒有使用Java了,因此代碼中可能存在導致此奇怪錯誤的問題。
我必須遍歷一個整數數組,以便生成和排序不同長度的隨機數組:
public static Log[][] eval(Integer[] sizes, Algorithm alg){
Log[][] logs = new Log[sizes.length][2];
for (int i = 0; i < sizes.length; i++) {
Log[] tmp = new Log[3];
Integer[] rand = randomArray(sizes[i]);
System.out.println("Before "+Arrays.toString(rand));
tmp[0] = new Log(sizes[i], rand);
tmp[1] = alg.insertionSort(rand);
tmp[2] = alg.selectionSort(rand);
System.out.println("After "+Arrays.toString(rand));
logs[i] = tmp;
}
return logs;
}
如您所見,有2個調試,它們將提供如下信息:
在[2,1,4,5,3]之前
在[1,2,3,4,5]之后
在[1,8,9,10,5,4,2,6,7,3]之前
在[1,2,3,4,5,6,7,8,9,10]之后
在[11,15,20,16,18,8,4,13,2,19,12,3,10,5,17,17,14,1,9,6,7]之前
在[1、2、3、4、5、6、7、8、9、10、11、12、13、14、15、16、17、18、19、20]之后
這很奇怪,因為我不更改蘭德值。 即使我在循環外放置了一個名為backup的Int數組並覆蓋它並在上一個日志中打印出來,它仍然是一個排序的數組。 我試圖解決這個問題超過一個小時,但找不到該錯誤。 它必須在索引1/2的算法方法之內,因為跳過這些行時,Before == After。 但是我不知道這是怎么回事,因為我只使用數組作為參數並返回一個Log對象。
這是一種算法方法:
public Log insertionSort(Integer[] sortieren) {
double startTime = System.nanoTime();
int temp;
for (int i = 1; i < sortieren.length; i++) {
temp = sortieren[i];
int j = i;
while (j > 0 && sortieren[j - 1] > temp) {
sortieren[j] = sortieren[j - 1];
j--;
}
sortieren[j] = temp;
}
double stopTime = System.nanoTime();
double time = stopTime - startTime;
Log log = new Log("Insertion-Sort", (time/1000000), sortieren);
return log;
}
這是我的日志類:
public class Log {
public String name;
public double time;
public int size;
public Integer[] sorted;
public Integer[] randArray;
public Log(String name, double time, Integer[] sorted){
this.name = name;
this.time = time;
this.sorted = sorted;
}
public Log(int size, Integer[] random){
this.size = size;
this.randArray = random;
}
}
稍后,我想通過以下方法對此進行評估:
public static void reportLogger(Log[][] log, boolean showArray){
for (int i = 0; i < log.length; i++) {
// Show Initial Array (0th Index) -> (size, array)
for (int j = 1; j <= 2 ; j++) {
Log tmp = log[i][j];
// 1st/2nd Index -> Insert/Selection -> name, time, sortedArray by using tmp.name ,etc..
System.out.println("---------------------");*/
}
}
該數組是一個輸入參數,但也可以在第一種排序方法alg.insertionSort(rand)
。 在這一點上,該數組成為排序后的數組-不再是隨機數組。 在點alg.selectionSort(rand)
,它要做的就是對已排序的數組rand
進行排序。 為了比較性能,您應該復制rand
數組:
tmp[0] = new Log(sizes[i], rand);
Integer[] array_copy_1 = Array.copyof(rand, rand.size)
tmp[1] = alg.insertionSort(array_copy_1);
Integer[] array_copy_2 = Array.copyof(rand, rand.size)
tmp[2] = alg.selectionSort(array_copy_2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.