C#: Good/best implementation of Swap method

前端 未结 6 1483
醉话见心
醉话见心 2020-12-06 10:33

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 met

6条回答
  •  借酒劲吻你
    2020-12-06 11:22

    Use:

    void swap(int &a, int &b)
    {
        // &a != &b
        // a == b OK
        a ^= b;
        b ^= a;
        a ^= b;
        return;
    }
    

    I did not realize I was in the C# section. This is C++ code, but it should have the same basic idea. I believe ^ is XOR in C# as well. It looks like instead of & you may need "ref"(?). I am not sure.

提交回复
热议问题