c# - 如何对数组中的奇数进行升序排序?

标签 c# arrays sorting

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

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

预期的结果是:

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

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

挑战状态:

You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.

到目前为止,这是我的代码,请放轻松,我正处于编程的开始阶段。

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

最佳答案

检查这段代码。添加为评论的解释

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

关于c# - 如何对数组中的奇数进行升序排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51178272/

相关文章:

javascript - 如何使用forEach循环javascript对对象数组进行排序

c# - 比较具有不同项目类型的集合

c# - 在 C# 3.5 中,如何将调用对象的方法作为参数传递

C# 泛型和类型检查混淆

c# - 如何为基于策略模式的应用程序编写清晰优雅的代码?

java - 尝试创建用户输入的数组列表时出现 ArrayIndexOutOfBoundsException

java - 交换数组中对应的元素

c - 分割数组中的数字

java - 如何按字母顺序对名称数组列表进行排序,但以数字开头的名称必须排在最后

c++ - 在 C++ 中搜索按字典顺序排序的 vector<vector <int>>