乱序排列一个数组

///

    /// 乱序排列一个数组

    ///

    void Shuffle(string[] intArray)

    {

        for (int i = 0; i < intArray.Length; i++)

        {

            string temp = intArray[i];

            int randomIndex = Random.Range(0, intArray.Length);

            intArray[i] = intArray[randomIndex];

            intArray[randomIndex] = temp;

        }       

}

 

/// 

        /// 随机排序

        /// 

        /// 

        /// 

        public static int[] RandSort(int[] arry)

        {

            int[] arryNew = new int[arry.Length];

            Random rnd = new Random();

            int n = arry.Length;

            int i = 0;

            while (n > 0)

            {

                int index = rnd.Next(n);

                arryNew[i] = arry[index];

                arry[index] = arry[n-1];

                n--;

                i++;

            }

            return arryNew;

        }

//调用

int[] arry = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int[] arryRes = RandSort(arry);

 

 

如果要扩展到其他类型的数组队列,可以用泛型

//任意类型的队列随机排序

 public static T[] RandSort(T[] arry)

        {           

            T[] arryNew = new T[arry.Length];

            Random rnd = new Random();

            int n = arry.Length;

            int i = 0;

            while (n > 0)

            {

                int index = rnd.Next(n);

                arryNew[i] = arry[index];

                arry[index] = arry[n - 1];

                n--;

                i++;

            }

            return arryNew;

        }

//调用

string[] sArray = new string[] { "ab", "fs", "ta", "ds", "gd", "fafd" };

string[] sArrayRes = RandSort(sArray);

你可能感兴趣的:(乱序排列一个数组)