liyonghui

导航

洗牌算法

最近要做一个程序随机出数据的程序,最后找到了一个性能不错的算法 洗牌算法

 

Random ram = new Random()

 //随机交换
            int currentIndex;
            Product tempValue;
            for (int i = 0; i < listtemp.Count; i++)
            {
                currentIndex = ram.Next(0, listtemp.Count - i);
                tempValue = listtemp[currentIndex];
                listtemp[currentIndex] = listtemp[listtemp.Count - 1 - i];

 

 

/// <summary>
        /// 洗牌算法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listtemp"></param>
        public static List<T> Reshuffle<T>(List<T> listtemp)
        {
            //随机交换
            Random ram = new Random();
            int currentIndex;
            T tempValue;
            for (int i = 0; i < listtemp.Count; i++)
            {
                currentIndex = ram.Next(0, listtemp.Count - i);
                tempValue = listtemp[currentIndex];
                listtemp[currentIndex] = listtemp[listtemp.Count - 1 - i];
                listtemp[listtemp.Count - 1 - i] = tempValue;
            }

            return listtemp;

        }

 


posted on 2012-11-10 11:29  李永辉  阅读(144)  评论(0编辑  收藏  举报