首页 > 解决方案 > C# 按绝对值对数组进行排序不能按预期使用输入数组

问题描述

使用输入数组按绝对值对数组进行排序拒绝工作,但用一个简单的数组替换它是可行的。我不知道为什么它不起作用,我只是看不出有什么问题。

我需要结果是这样的:

输入:-5 4 8 -2 1

输出:1 -2 4 -5 8

    static void Main()
    {
        var sampleInput =  Console.ReadLine().Split().Select(int.Parse).ToArray();

        int[] x = sampleInput;
        int n = sampleInput.Length;
            int[] output = new int[n];
            string sOutput = string.Empty;
            int start = 0;
            int last = n - 1;

            while (last >= start)
            {
                n--;
                if (Math.Abs(x[start]) > Math.Abs(x[last]))
                {
                    output[n] = x[start++];
                }
                else
                {
                    output[n] = x[last--];
                }

                sOutput = output[n].ToString() + " " + sOutput;
            }

            Console.Write(sOutput);

    }

标签: c#arrayssorting

解决方案


为什么不

using System.Linq;

var sorted = new [] {-5, 4, 8, -2 , 1}.OrderBy(Math.Abs);

(当然要得到一个数组,你可以.ToArray()在最后加上一个)。

并通过你想要的:

var sampleInput =  Console.ReadLine().Split().Select(int.Parse).ToArray();
var sorted = sampleInput.OrderBy(Math.Abs);

推荐阅读