2016-11-13 90 views
0

隨着冒泡排序與2個不同的陣列

string[] z = { "arc", "banana", "cucumber", "deer", "elephant", "fiesta", "giga", "home", "idea", "jump" }; 
int[] y = { 189, 178, 65, 63, 200, 1000, 10, 15, 28, 20 }; 

我做冒泡排序的zy下令:

for (int i=0;i<=(y.length-2);i++){ 
       for (int j=(y.length-1); i<j;j--){ 
        if (y[j]<y[j-1]){ 
         int temp= y[j-1]; 
         y[j-1]=y[j]; 
         y[j]=temp; 
         String tempo=z[j-1]; 
         z[j-1]=z[j]; 
         tempo=z[j]; 
        } 
       } 
      } 
for (int i=y.length-1;i>0;i--){ 
System.out.println(z[i]);} 

打印後z的輸出爲:

跳,跳,跳,想法,想法,想法,想法,首頁,家,家

爲什麼排序刪除z的某些值?

回答

0

您沒有使用字符串數組的臨時變量。有了您的代碼保存在tempoz[j-1]的內容,但你不要把它寫回磁盤陣列:

而不是

String tempo=z[j-1]; 
z[j-1]=z[j]; 
tempo=z[j]; 

試試這個:

String tempo = z[j - 1]; 
z[j - 1] = z[j]; 
z[j] = tempo; 

而在你的輸出循環,你有一個off by one error。使用>=0

for (int i=y.length-1;i>=0;i--) 
+0

好的,謝謝。這是一個noob錯誤。 –