【问题标题】:How to sort ascending only odd numbers in array?如何仅对数组中的奇数进行升序排序?
【发布时间】:2018-07-04 17:01:17
【问题描述】:

我只想排序奇数而不移动偶数。例如,如果我的输入是:

[5, 3, 2, 8, 1, 4]

预期结果是:

[1, 3, 2, 8, 5, 4]

我是 C# 新手,在 Internet 上遇到了一个令我困惑的挑战。我已经尝试了几个小时,我想在

中学习这个概念

挑战说明:

你有一个数字数组。你的任务是对升序的奇数进行排序,但偶数必须在它们的位置上。零不是奇数,你不需要移动它。如果你有一个空数组,你需要返回它。

这是我目前的代码,请放心,我正处于编程的初级阶段。

public static int[] SortArray(int[] array)
{
    var dict = new Dictionary<int, int>();
    var dict2 = new Dictionary<int, int>();

    for (int i = 0; i < array.Length; i++)
    {
        int j =0;
        if (array[i] % 2 != 0)
        {
            dict.Add(array[i], i+1);
        }
        else
        {
            dict2.Add(array[i], i+1);
        }
    }
    var result = dict.OrderBy(x => x.Key);
    Dictionary<int, int> resultDic = result.Union(dict2)
      .GroupBy(x => x.Key).ToDictionary(o => o.Key, o => o.Key);
}

public static void Main()
{
    SortArray(new int[] { 5, 3, 2, 8, 1, 4});
}

【问题讨论】:

  • 似乎您应该能够使用任何现有的就地排序算法 - 只需完全忽略(跳过)包含偶数值的位置。
  • 欢迎来到 StackOverflow;我注意到您的问题中没有 question,只有一段代码和一个问题陈述。 您的具体问题是什么?如果您的代码有效并且您希望获得评论,请将其发布在代码审查网站上,而不是本网站上。如果您的代码不起作用,请询问有关问题的具体问题

标签: c# arrays sorting


【解决方案1】:

检查此代码。添加为 cmets 的说明

public static int[] SortArray(int[] array)
{
    //temp variable for holding larger value for switching
    int temp = 0;

    for (int i = 0; i < array.Length; i++)
    {
        //If the value is 'even' continue with outer loop
        if(array[i] % 2 == 0)
           continue;

        //Inner loop to compare array values
        for(int j = (i + 1); j < array.Length; j++)
        {
            //If this value is not even do comparison
            if(array[j] % 2 != 0)
            {
                //If the left value is greater than the right value
                //swap them
                if(array[i] > array[j])
                {
                   temp = array[i];
                   array[i] = array[j];
                   array[j] = temp;
                }
            }
        }
    }

    return array;
}

public static void Main()
{
    SortArray(new int[] { 5, 3, 2, 8, 1, 4});
}

【讨论】:

    【解决方案2】:

    您可以在开始之前通过索引数字来使用 linq:

    var nums = new[] { 5, 3, 2, 8, 1, 4 };
    var indexedNums = nums.Select((num, idx) => new { num, idx }).ToList();
    

    然后将这些索引数字排序为偶数和赔率:

    var evens = indexedNums.Where(x => x.num % 2 == 0);
    var odds = indexedNums.Where(x => x.num % 2 == 1);
    

    将奇数(索引)按其值排序:

    var sortedOdds = odds.OrderBy(x => x.num); //sort the odd numbers by their value
    

    使用odds 序列(按索引排序)压缩此序列,从sortedOdds 获取数字,从odds 获取索引

    var reindexedOdds = sortedOdds.Zip(odds, (o1, o2) => new { o1.num, o2.idx });
    

    ...然后将这些reindexedOdds 放入带有索引的evens 从上面的序列中,按索引排序,然后选择数字。

    var endSequence = evens.Concat(reindexedOdds).OrderBy(x => x.idx).Select(x => x.num);
    

    【讨论】:

      【解决方案3】:

      虽然其他解决方案在形式上是正确的,但大多数都不是有效的,具有O(n^2) 时间复杂度。

      另一种(更省时)的方法应该意味着使用两个列表:第一个将包含奇数的索引,第二个将存储已排序的奇数。

      public static int[] SortArray(int[] array)
      {
          var sortedOdds = new List<int>(array.Length);
          var oddsIndexes = new List<int>(array.Length);
          var newArray = new int[array.Length];
      
          for(var i = 0; i < array.Length; i++) // O(n)
          {
              var value = array[i];
              if(value % 2 == 1)
              {
                  sortedOdds.Add(value);
                  oddsIndexes.Add(i);
              } else
              {
                  newArray[i] = value;
              }
          }
      
          sortedOdds.Sort(); // average complexity O(n log n)
      
          for(var j = 0; j < sortedOdds.Count; j++) // O(n)
          {
              var value = sortedOdds[j];
              var index = oddsIndexes[j];
              newArray[index] = value;
          }
      
          return newArray;
      }
      

      这会将复杂度降低到平均O(n log n) 时间。

      【讨论】:

        猜你喜欢
        • 2022-12-13
        • 1970-01-01
        • 2019-09-08
        • 1970-01-01
        • 2010-09-10
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多