最有效的方法随机"排序" (随机播放)的整数在C#中的列表 [英] Most efficient way to randomly "sort" (Shuffle) a list of integers in C#

查看:131
本文介绍了最有效的方法随机"排序" (随机播放)的整数在C#中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要随机'排序'以最有效的方式整数(0-1999)的列表。任何想法?

目前,我做这样的事情:

 布尔[] = bIndexSet新布尔[iItemCount]对(INT iCurIndex = 0; iCurIndex&下; iItemCount; iCurIndex ++)
{
    INT iSwapIndex = random.Next(iItemCount);
    如果(bIndexSet [iSwapIndex&放大器;!&安培;!iSwapIndex = iCurIndex)
    {
        INT ITEMP =值[iSwapIndex]
        值[iSwapIndex] =值[iCurIndex]
        值[iCurIndex] =值[iSwapIndex]
        bIndexSet [iCurIndex] = TRUE;
        bIndexSet [iSwapIndex] = TRUE;
    }
}


解决方案

一个良好的线性时间的洗牌算法是渔民耶茨洗牌

你会与你的算法发现的一个问题是,当你靠近洗牌结束后,你的循环将花费大量的时间寻找尚未被交换随机选取的元素。这可能需要时间的不确定量,一旦它到达交换的最后一个元素。

此外,它看起来就像如果有奇数个元素进行排序的你的算法将永远不会终止。

I need to randomly 'sort' a list of integers (0-1999) in the most efficient way possible. Any ideas?

Currently, I am doing something like this:

bool[] bIndexSet = new bool[iItemCount];

for (int iCurIndex = 0; iCurIndex < iItemCount; iCurIndex++)
{
    int iSwapIndex = random.Next(iItemCount);
    if (!bIndexSet[iSwapIndex] && iSwapIndex != iCurIndex)
    {
        int iTemp = values[iSwapIndex];
        values[iSwapIndex] = values[iCurIndex];
        values[iCurIndex] = values[iSwapIndex];
        bIndexSet[iCurIndex] = true;
        bIndexSet[iSwapIndex] = true;
    }
}

解决方案

A good linear-time shuffling algorithm is the Fisher-Yates shuffle.

One problem you'll find with your proposed algorithm is that as you near the end of the shuffle, your loop will spend a lot of time looking for randomly chosen elements that have not yet been swapped. This may take an indeterminate amount of time once it gets to the last element to swap.

Also, it looks like your algorithm will never terminate if there are an odd number of elements to sort.

这篇关于最有效的方法随机&QUOT;排序&QUOT; (随机播放)的整数在C#中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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