【问题标题】:Custom sorting array - smaller values between larger values自定义排序数组 - 较大值之间的较小值
【发布时间】:2021-05-04 12:34:56
【问题描述】:

我有一个数组 A,其值为:{10, 12, 6, 14, 7},我有一个数组 B,其值为:{1, 8, 2}
我已经按升序对数组 B 进行了排序,然后将两个数组合并到一个新数组 C 中,如以下代码所示 -

static void Main()
{
    int A[] = {10, 12, 6, 14, 7};
    int B[] = {1, 8, 2};

    Array.Sort(B);
    var myList = new List<int>();
    myList.AddRange(A);
    myList.AddRange(B);
    int[] C = myList.ToArray();

    //need values in this order: 10, 1, 12, 2, 8, 6, 14, 7
}

现在我想这样对数组 C 进行排序:10、1、12、2、8、6、14、7

较小的值应该在较大的值之间,例如:1 介于 10 和 12 之间,2 介于 12 和 8 之间,6 介于 8 和 14 之间,依此类推。

如何在 C# 中做到这一点?

如果需要递归,如何将其添加到代码中?

【问题讨论】:

  • 如果您拥有的唯一标准是较小的数字必须在较大的数字之间,那么为什么它必须是 [10, 1, 12, 2, 8, 6, 14 , 7] 在你的例子中?从技术上讲,[.. 1, 12, 2 ..] 违反了这一要求。我们需要进一步澄清。
  • 如果您正在寻找与上面类似的精确输出,我们能否提供更多示例输入和输出?

标签: c# arrays sorting


【解决方案1】:

我从您的示例中了解到的是,您正在尝试在大值和小值之间交替,以使小值始终小于左侧和右侧的数字。我在下面编写了一个算法来做到这一点,但是它不会产生您要求的完全相同的结果。但是我相信它确实符合要求。

分散的7 被认为是序列中的下一个最小数字,但它后面没有数字。根据您的示例,这似乎是允许的。

调用

    int[] A = { 10, 12, 6, 14, 7 };
    int[] B = { 1, 8, 2 };

    var result = Sort(A, B);

Sort方法

    public static int[] Sort(int[] A, int[] B)
    {
        var result = new int[A.Length + B.Length];
        var resultIndex = 0;

        Array.Sort(A);
        Array.Sort(B);

        //'Pointer' for lower index, higher index
        var aLeft = 0;
        var aRight = A.Length-1;

        var bLeft = 0;
        var bRight = B.Length - 1;

        //When Items remain in both arrays
        while (aRight >= aLeft && bRight >= bLeft)
        {
            //Add smallest
            if (resultIndex % 2 > 0)
            {
                if (A[aLeft] < B[bLeft])
                    result[resultIndex++] = A[aLeft++];
                else
                    result[resultIndex++] = B[bLeft++];

            }
            //Add largest
            else
            {
                if (A[aRight] > B[bRight])
                    result[resultIndex++] = A[aRight--];
                else
                    result[resultIndex++] = B[bRight--];
            }
        }

        //When items only in array A
        while (aRight >= aLeft)
        {
            //Add smallest
            if (resultIndex % 2 > 0)
                result[resultIndex++] = A[aLeft++];
            //Add largest
            else
                result[resultIndex++] = A[aRight--];

        }


        //When items remain only in B
        while (bRight >= bLeft)
        {
            //Add smallest
            if (resultIndex % 2 > 0)
                result[resultIndex++] = B[bLeft++];
            //Add largest
            else
                result[resultIndex++] = B[bRight--];

        }
        return result;
    }

结果

[14, 1, 12, 2, 10, 6, 8, 7]

【讨论】:

    猜你喜欢
    • 2020-07-10
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 2020-02-24
    相关资源
    最近更新 更多