How can I swap two values of an array in C#?
Asked Answered
E

7

12

I have an array of int containing some values starting from index 0. I want to swap two values, for example, the value of index 0 should be swapped with the value of index 1. How can I do this in the C# array?

Etrem answered 3/5, 2017 at 11:41 Comment(0)
H
41

Use a tuple:

int[] arr = { 1, 2, 3 };
(arr[0], arr[1]) = (arr[1], arr[0]);
Console.WriteLine(string.Format($"{arr[0]} {arr[1]} {arr[2]}")); // 2 1 3

Tuples are available in C# 7.0. See Tuple types (C# reference).

Hightower answered 10/7, 2020 at 18:45 Comment(0)
S
12

You could create an extension method that would work for any array:

public static void SwapValues<T>(this T[] source, long index1, long index2)
{
    T temp = source[index1];
    source[index1] = source[index2];
    source[index2] = temp;
}
Sensor answered 3/5, 2017 at 12:10 Comment(0)
T
10

If you really only want to swap, you can use this method:

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 temp = array[x];
        array[x] = array[y];
        array[y] = temp;    


        return true;
}

x and y are the array indexes to be swapped.

If you want to swap with any type of array, then you can do it like this:

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 temp = objectArray[x];
        objectArray[x] = objectArray[y];
        objectArray[y] = temp ;
        

        return true;
}

And you can call it like:

string[] myArray = {"1", "2", "3", "4", "5", "6"};
        
if(!swap<string>(myArray, 0, 1)) {
    Console.WriteLine("x or y are out of range!");
}
else {
    //print myArray content (values will be swapped)
}
Takamatsu answered 3/5, 2017 at 11:52 Comment(0)
C
2

Swap only two values only once or want to do the same for the entire array:

Assuming that you only want to swap only two only once and is of type integer, then you can try this:

    int temp = 0;
    temp = arr[0];
    arr[0] = arr[1];
    arr[1] = temp;
Craft answered 3/5, 2017 at 11:54 Comment(0)
S
2

It’s possible to swap two values by the XOR operator (math magic), like below:

public static void Swap(int[] a, int i, int k)
{
    a[i] ^= a[k];
    a[k] ^= a[i];
    a[i] ^= a[k];
}
Sallie answered 10/5, 2021 at 18:34 Comment(1)
It is the XOR swap algorithm.Reexamine
A
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
}

call this function and print elemet

Amid answered 3/5, 2017 at 11:52 Comment(0)
M
1

I just wrote something similar, so here is a version that

  • uses generics so that it works on ints, strings etc,
  • uses extension methods
  • comes with a test class

Enjoy :)

[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; 
    }
}
Mannino answered 3/5, 2017 at 12:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.