2014-10-03 79 views
0

如何交換給定整數數組和兩個整數值的兩個數組值?交換數組元素值

我使用的代碼

public class Q1K { 
    void swapElements(int[] array, int index1, int index2){ 
     int index3= array[index1]; 
     array[index1]=array[index2]; 
     array[index2]= array[index3]; 
    } 
} 

很抱歉,如果我的問題是缺少信息/費解

+0

您提供輸入和預期輸出將有助於獲得清晰的想法 – 2014-10-03 10:15:47

+0

你的問題不清楚。你能提一下你的期望嗎? – 2014-10-03 10:16:41

回答

2

它應該是,

int temp = array[index1]; // its not a index, its a value at a particular index. 
array[index1]=array[index2]; 
array[index2]= temp; 

您使用的命名規則是安靜混亂index3,它實際上應該是一個臨時變量,用於swapping

1

您的回答非常接近。看看這個解決方案...

public class Q1K { 
    void swapElements(int[] array, int index1, int index2){ 
     int val = array[index1]; 
     array[index1] = array[index2]; 
     array[index2] = val; 
    } 
} 
2

array[index3];將再次返回數組中的值。所以你需要把它寫成index3

明智地命名變量以避免混淆, 還記得[]大括號內的值表示始終的位置。

Learn More關於交換數組。

3

您已經知道您需要一個臨時變量來執行Java中的基本交換。但變量的命名(你的案例中的index3)表明你混淆了事物;我們的目標不是臨時存儲您的數組的索引,而是由該索引代表的 - 否則,它將被覆蓋(並因此丟失)。在交換的「第3步」中你想要做的是恢復臨時值本身,而不是索引後面的值。

所以:

void swapElements(int[] array, int index1, int index2){ 
     int tempValue = array[index1]; 
     array[index1] = array[index2]; 
     array[index2] = tempValue; 
} 
1
public class Q1K { 
    void swapElements(int[] array, int index1, int index2){ 
     int index3= array[index1]; 
     array[index1]=array[index2]; 
     array[index2]= index3; 
    } 
} 

確保你的名字你的變量,使得他們閱讀代碼的時候纔有意義。從你的代碼,INDEX3聽起來像排列的指標,但在代碼方面真的不是:)

0

還有另一種方式,不需要使用臨時變量:

void swapElements(int[] array, int ix1, int ix2){ 
    array[ix1] = array[ix1] + array[ix2]; 
    array[ix2] = array[ix1] - array[ix2]; 
    array[ix1] = array[ix1] - array[ix2]; 
}