C#:Swap方法的良好/最佳实现 [英] C#: Good/best implementation of Swap method
问题描述
我阅读了关于卡洗牌的帖子,并且在许多洗牌和排序中您需要在列表或数组中交换两个项目的算法.但是,一种有效且高效的Swap方法是什么样的?
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?
比方说T[]
和List<T>
.您如何最好地实现在这两个项目中交换两个项目的方法?
Let's say for a T[]
and for a List<T>
. 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?
推荐答案
好,您发布的代码(ref cards[n]
)只能与数组(而不是列表)一起使用-但您可以简单地使用(其中bar
是两个值):
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.
这篇关于C#:Swap方法的良好/最佳实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!