c# - 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);
(当然要得到一个数组,你可以.ToArray()
在最后加上一个)。
并通过你想要的:
var sampleInput = Console.ReadLine().Split().Select(int.Parse).ToArray();
var sorted = sampleInput.OrderBy(Math.Abs);
推荐阅读
- android - Flutter:当其他小部件可用时,ListView 的高度会降低
- sql - 如何在 SQL Server 中分隔逗号分隔值:对当前查询的改进?
- gridview - 单击下一页时Gridview正在清除
- jenkins - jenkins 在特定代理/节点上执行 shell
- ruby-on-rails - HTTPParty 文件上传
- javascript - 列表项组件未在反应 js 中的状态更改时更新
- vue.js - 子路由中的 vue-router 命名视图不起作用
- php - 从表单获取数据的 SQL 更新查询未运行
- wso2 - 在 WSO2 EI 6.4 中批量导入注册表工件
- python - 无法使用 api 在 Jira 中创建项目,每当我尝试运行此脚本时都会收到 400 错误代码。谁能帮我解决这个问题