永发信息网

C# Int数组有无序的正负数,只考虑获取正数,并且正数在前,负数在后,正数相对顺序不便,负数无所谓

答案:2  悬赏:0  手机版
解决时间 2021-04-03 23:14
  • 提问者网友:留有余香
  • 2021-04-03 07:18
C# Int数组有无序的正负数,只考虑获取正数,并且正数在前,负数在后,正数相对顺序不便,负数无所谓
最佳答案
  • 五星知识达人网友:千夜
  • 2021-04-03 08:31
int[] list = { 1, -2, -1, -3, 4, 5, 6, -7, 8, 9};
int[] newlist = new int[list.Length];
int index = 0;
for (int i = 0; i < list.Length; i++)
{
if (list[i] > 0)
{
newlist[index] = list[i];
index++;
}
}
for (int i = 0; i < list.Length; i++)
{
if (list[i] < 0)
{
newlist[index] = list[i];
index++;
}
}
for (int i = 0; i < newlist.Length; i++)
{
Console.Write("{0,4}", newlist[i]);
}
Console.Read();追问不要借助其他新的数组。
怎么减少一次循环?

追答    //那就这样吧,不过要多定义一个整数index 
        int[] list = { 1, -2, -1, -3, 4, 5, 6, -7, 8, 9 };
            int index = 0;
            for (int i = 0; i < list.Length; i++)
           {
               if (list[i] > 0)
               {
                    if (index != i)
                    {
                        list[index] = list[i] + list[index];
                        list[i] = list[index] - list[i];
                        list[index] = list[index] - list[i];
                    }
                    index++;
                }
            }
            for (int i = 0; i < list.Length; i++)
            {
                Console.Write("{0,4}", list[i]);
            }
全部回答
  • 1楼网友:走死在岁月里
  • 2021-04-03 09:06
            int[] a = { 1, -2, -1, -3, 4, 5, 6, -7, 8, 9 };
            int[] p = a.Where(i => i > 0).ToArray();
            int[] n = a.Where(j => j < 0).ToArray();
            Array.Copy(p, a, p.Length);
            Array.Copy(n, 0, a, p.Length, n.Length);
            //int[] a 中存放着结果
 追问不要借助其他新的数组。

不过还是谢谢你。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯