1. 程式人生 > >將一個數組中的各個元素拼接組合,得到數字最大的組合

將一個數組中的各個元素拼接組合,得到數字最大的組合

將一個數組中的各個元素拼接組合,得到數字最大的組合。
    如:int[] arr = new int[5] {1, 26, 56, 894, 5648};
    拼接組合後最大的數為 564889456261 --> 5648 894 56 26 1 的拼接結構
public string GetArraySortMaxNumber(int[] nums)
    {
        int temp;
        for (int i = 1; i < nums.Length; i++)
        {
            temp = nums[i];
            for (int j = i - 1; j >= 0; j--)
            {
                bool insert = true;
                string a = nums[j].ToString();
                string b = temp.ToString();
                
                //36 365 -- 36 367 的兩種特殊情況(處理如下)
                //補齊短的數字至和長的數字長度相同,補上的數字位短的數字的最後一位數
                if (a.Length > b.Length)
                {
                    b = AddLastStr(a, b);
                }
                else if (a.Length < b.Length)
                {
                    a = AddLastStr(b, a);
                }

                for (int x = 0; x < a.Length; x++)
                {
                    int aNum = a[x];
                    int bNum = b[x];

                    if (bNum > aNum)
                        insert = false;
                }

                //使用插入排序
                if (!insert)
                {
                    nums[j + 1] = nums[j];
                    if (j == 0)
                    {
                        nums[0] = temp;
                        break;
                    }
                }
                else
                {
                    nums[j + 1] = temp;
                    break;
                }
            }
        }
        
        string result = string.Empty;
        foreach (var item in nums)
        {
            result += item;
        }

        return result;
    }