数组乱序算法

    public static class ArrayHelper
    {
        /// <summary>
        /// 数组乱序
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr"></param>
        public static T[] RandomSort<T>(this T[] arr)
        {
            var count = arr.Length;
            var newArr = new T[count];
            int newArrayItemCount = 0, originalArrayIndex = 0, newArrayIndex = 0;
            Random random = new Random();
           
            do
            {
                var balanceCount = count - newArrayItemCount;
                originalArrayIndex = random.Next(balanceCount);
                newArr[newArrayIndex++] = arr[originalArrayIndex];
                newArrayItemCount++;
                arr[originalArrayIndex] = arr[balanceCount - 1];
            } while (count > newArrayItemCount);

            return newArr;
        }
    }

 

posted @ 2017-03-27 19:17  zslm___  阅读(828)  评论(0编辑  收藏  举报