2014-02-20 79 views
0

我想寫一個方法,在兩個特定的索引之間顛倒數組中的輸入。但是,它會一直返回原始數組,就好像它在測試時沒有任何變化。有什麼想法嗎?顛倒兩個索引之間的數組的一部分

public static void reverse (char[] ar, int i, int j) { 
    char[] arTwo= new char[ar.length]; 
    for (int x =0; x < ar.length; x++){  
     arTwo[x]= ar[x]; 
    } 
    int up =i; 
    int down = j; 
    while (up> j) { 
     ar[up] = arTwo[down]; 
     up++; 
     down--; 
    } 

} 
+3

什麼是變量'countUp'? – skiwi

+0

這是糟糕的編輯,應該是不會countup。 – user2792660

+0

你的while循環不應該有'up j'的條件嗎? – ujvl

回答

0

爲什麼不交換原始數組中的項目?

for (int x=0; x<(j-i)/2; x++) 
{ 
    int index1 = i+x; 
    int index2 = j-x; 
    char temp = ar[index1]; 
    ar[index1] = ar[index2]; 
    ar[index2] = temp; 
} 
4

while循環迴路,而條件是true,但假設i < jup > j是從一開始就false,所以沒有重複發生。

嘗試

while (up < down) { 

所以up中間滿足down