C#按绝对值对数组排序不适用于输入数组

-3 c# arrays sorting

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

我需要的结果是这样的:

输入: -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);

    }
Run Code Online (Sandbox Code Playgroud)

zai*_*man 7

为什么不

using System.Linq;

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

(当然要获得一个数组,您可以.ToArray()在末尾添加一个)。

并传递您想要的:

var sampleInput =  Console.ReadLine().Split().Select(int.Parse).ToArray();
var sorted = sampleInput.OrderBy(Math.Abs);
Run Code Online (Sandbox Code Playgroud)