C# 生成陣列 由小排到大 個位數由大排到小

namespace ArraySortByDigits
{
    class Program
    {
        /// <summary>
        /// 隨機產生 10 個數字,由小到大排序,再依個位數由大到小排序。
        /// <list type="bullet">
        /// <see href="https://rovingwind.synology.me/?p=245">MyWebSite</see>
        /// </list>        
        /// </summary>        
        static void Main(string[] args)
        {            
            int[] numArr = mNonRepeatArray(10, 30);

            Console.Write("產生隨機陣列:");
            for (int i = 0; i < numArr.Length; i++)
            {
                Console.Write(numArr[i] + " ");
            }
            Console.WriteLine();

            Array.Sort(numArr); // 排序小到大
            Console.Write("陣列 after  Sort:");
            for (int i = 0; i < numArr.Length; i++)
            {
                Console.Write(numArr[i] + " ");
            }
            Console.WriteLine();

            numArr = mSort(numArr);
            Console.Write("陣列 after mSort:");
            for (int i = 0; i < numArr.Length; i++)
            {
                Console.Write(numArr[i] + " ");
            }
            Console.Read();
        }

        /// <summary>
        /// 隨機產生不重覆的數字陣列
        /// </summary>        
        /// <returns>int[]</returns>
        static int[] mNonRepeatArray(int n, int max)
        {
            Random ra = new Random();
            int[] numArr = new int[n];
            for (int i = 0; i < numArr.Length; i++)
            {
                numArr[i] = ra.Next(1, max);
                for (int j = 0; j < i; j++)
                {
                    while (numArr[j] == numArr[i]) // 檢查重覆
                    {
                        numArr[i] = ra.Next(1, max);
                        j = 0; // 從頭開始比對
                    }
                }
            }
            return numArr;
        }

        /// <summary>
        /// 將陣列依個位數由大到小排序
        /// </summary>        
        /// <returns>int[]</returns>
        static int[] mSort(int[] numArr)
        {
            for (int i = 0; i < numArr.Length; ++i)
            {
                for (int j = 0; j < i; ++j)
                {
                    if (numArr[i] / 10 == numArr[j] / 10)
                    {
                        if (numArr[j] % 10 < numArr[i] % 10)
                        {
                            int temp = numArr[i];
                            numArr[i] = numArr[j];
                            numArr[j] = temp;
                        }
                    }
                }
            }
            return numArr;
        }
    }
}

發佈留言