为什么在使用排序随机造成不[无法进行排序IComparer.Compare错误] [英] Why does using Random in Sort causing [Unable to sort IComparer.Compare error]

查看:755
本文介绍了为什么在使用排序随机造成不[无法进行排序IComparer.Compare错误]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用任何code洗牌字节(列表)的列表:

I tried shuffling a list of byte (List) using either code:

myList.Sort((a, b) => this._Rnd.Next(-1, 1));

myList.Sort(delegate(byte b1, byte b2)
{
    return this._Rnd.Next(-1, 1);
});

和他们扔了以下错误:

无法排序因为IComparer.Compare()方法返回不一致的结果。无论是相对于另一个值产生不同结果的价值并不比等于本身,或者一个值反复。 X:{0},X的类型:{1},IComparer的。{2}

Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. x: '{0}', x's type: '{1}', IComparer: '{2}'.

什么是错的使用随机,而不是字节的比较功能?

What is wrong with using a random rather than the compare function of byte?

我试着使用LINQ功能,而不是和它的作品。

I tried using LINQ function instead and it works.

var myNewList = myList.OrderBy(s => Guid.NewGuid());
var myNewList = myList.OrderBy(s => this._Rnd.NextDouble());

我看过这些方法都慢于费雪耶茨洗牌给O(n)的唯一运行。但只是想知道如何使用排序功能和随机的。

I did read that these methods are slower than Fisher–Yates shuffle giving O(n) runtime only. But was just wondering on using the Sort function and random.

推荐答案

由于作为错误说,随机并不一致。你必须有一个比较器给出相同的参数时,它总是返回相同的结果。否则,排序不会是一致的。

Because as the error says, Random is not consistent. You must have a comparer that always returns the same result when given the same parameters. otherwise the sort will not be consistent.

克努特有它非常有效的插入排序随机排序算法,但你交换与HHE现有阵列随机选择的位置的值。

Knuth has a random sort algorithm which worked like an insertion sort, but you swapped the value with a randomly chosen location in hhe existing array.

这篇关于为什么在使用排序随机造成不[无法进行排序IComparer.Compare错误]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆