2017-05-03 1354 views

回答

3

如果你真的只想要交換,你可以用這個方法:

public static bool swap(int x, int y, ref int[] array){ 

     // check for out of range 
     if(array.Length <= y || array.Length <= x) return false; 


     // swap index x and y 
     var buffer = array[x]; 
     array[x] = array[y]; 
     array[y] = buffer; 


     return true; 
} 

x和y的indizies,應當調換。

如果你想與任何類型的陣列來交換,那麼你可以做這樣的:

public static bool swap<T>(this T[] objectArray, int x, int y){ 

     // check for out of range 
     if(objectArray.Length <= y || objectArray.Length <= x) return false; 


     // swap index x and y 
     T buffer = objectArray[x]; 
     objectArray[x] = objectArray[y]; 
     objectArray[y] = buffer; 


     return true; 
} 

你可以這樣調用它:

string[] myArray = {"1", "2", "3", "4", "5", "6"}; 

if(!swap<string>(myArray, 0, 1)) { 
    Console.WriteLine("x or y are out of range!"); 
    return; 
} 
1
static void SwapInts(int[] array, int position1, int position2) 
{  
    int temp = array[position1]; // Copy the first position's element 
    array[position1] = array[position2]; // Assign to the second element 
    array[position2] = temp; // Assign to the first element 
} 

調用這個函數和打印elemet

1

只交換兩個值只有一次或想要爲整個陣列做同樣的事情。

假設你只希望交換隻有兩個只有一次,是整數類型的,那麼你可以試試這個:

int temp=0; 
    temp=arr[0]; 
    arr[0]=arr[1]; 
    arr[1]=temp; 
0

我只寫類似的東西,所以這裏是一個版本,

  • 使用泛型,使其適用於整數,字符串等,
  • 使用擴展方法
  • 配有測試類

享受:)

[TestClass] 
public class MiscTests 
{ 
    [TestMethod] 
    public void TestSwap() 
    { 
     int[] sa = {3, 2}; 
     sa.Swap(0, 1); 
     Assert.AreEqual(sa[0], 2); 
     Assert.AreEqual(sa[1], 3); 
    } 
} 

public static class SwapExtension 
{ 
    public static void Swap<T>(this T[] a, int i1, int i2) 
    { 
     T t = a[i1]; 
     a[i1] = a[i2]; 
     a[i2] = t; 
    } 
} 
4

您可以創建一個擴展方法,將任何陣列

public static void SwapValues<T>(this T[] source, long index1, long index2) 
{ 
    T temp = source[index1]; 
    source[index1] = source[index2]; 
    source[index2] = temp; 
} 
工作