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);
}

为什么不

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

(当然,要获得Array,您可以在末尾添加.ToArray()(。

通过你想要的:

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

这是您的解决方案。

var array = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
var sorted = array.OrderBy(Math.Abs);
foreach (int element in sorted)
{
Console.WriteLine(element);
}

谨致问候,同学?

最新更新