Svish Svish - 4 months ago 11
C# Question

C#: Good/best implementation of Swap method

I read this post about card shuffling and in many shuffling and sorting algorithms you need to swap two items in a list or array. But what does a good and efficient Swap method look like?

Let's say for a

and for a
. How would you best implement a method that swaps two items in those two?

Swap(ref cards[i], ref cards[n]); // How is Swap implemented?


Well, the code you have posted (ref cards[n]) can only work with an array (not a list) - but you would use simply (where foo and bar are the two values):

static void Swap(ref int foo, ref int bar) {
    int tmp = foo;
    foo = bar;
    bar = tmp;

Or possibly (if you want atomic):

Interlocked.Exchange(ref foo, ref bar);

Personally, I don't think I'd bother with a swap method, though - just do it directly; this means that you can use (either for a list or for an array):

int tmp = cards[n];
cards[n] = cards[i];
cards[i] = tmp;

If you really wanted to write a swap method that worked on either a list or an array, you'd have to do something like:

static void Swap(IList<int> list, int indexA, int indexB)
    int tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;

(it would be trivial to make this generic) - however, the original "inline" version (i.e. not a method) working on an array will be faster.