打印最小值然后打印最高值

时间:2017-12-02 11:19:27

标签: c# console

输入

[1,5,3,7,2,10,15,9]

输出

[1,15,2,10,3,9,5,7]

逻辑是[1st smallest value, 1st highest value, 2nd smallest value, 2nd highest value, ...]

如何在C#中实现它?

3 个答案:

答案 0 :(得分:2)

另一种解决方案:

public static IEnumerable<T> SmallestGreatestSequence<T>(
    this IEnumerable<T> source)
{
    var ordered = source.OrderBy(i => i).ToList();
    var ascendingIndex = 0;
    var descendingIndex = ordered.Count - 1;

    while (ascendingIndex < descendingIndex)
    {
        yield return ordered[ascendingIndex++];
        yield return ordered[descendingIndex--];
    }

    if (ascendingIndex == descendingIndex)
        yield return ordered[ascendingIndex];
}

你可以这样使用它:

var someArray = new[] { 1, 5, 3, 7, 2, 10, 15, 9 };
var sortedArray = someArray.SmallestGreatestSequence().ToArray();

答案 1 :(得分:1)

如果您对基于LINQ的解决方案感到满意,可以选择以下解决方案。

var input = new int[] { 1, 5, 3, 7, 2, 10, 15, 9, 6 };

var sorted = input
    .OrderBy(z => z)
    .ToList();

var zippedInOrder = sorted.Take(input.Length / 2)
                        .Zip(
                            Enumerable.Reverse(sorted).Take(input.Length / 2),
                            (a, b) => new int[] { a, b });

var inOrder = zippedInOrder.SelectMany(z => z);

if (input.Length % 2 == 1)
{
    // Add the 'middle' element (sort order wise) 
    inOrder = inOrder.Concat(new List<int> { sorted[input.Length / 2] });
}

var finalInOrder = inOrder.ToList();

// To test
Console.WriteLine(string.Join(",", finalInOrder));

代码对输入数据进行排序,然后使用较大的数字和Zip s取大数字。然后SelectMany用于将数据投影到单个IEnumerable中。 Concat用于添加剩余的中间项(如果Length是奇数)。

答案 2 :(得分:0)

我不知道这是如何与SQL或MySQL相关的,但由于第一个标签是C#,这里有一个解决方案:

var inputSorted = input.OrderBy( i => i ).ToArray();
var output = new List<int>();

//go with index to the half of the array
for ( int i = 0; i < inputSorted.Length / 2; i++ )
{
   //add the i-th lowest number
   output.Add( inputSorted[i] );
   //add the i-th highest number
   output.Add( inputSorted[inputSorted.Length - i - 1] );
}

//if the length of the array is odd, add the single left out number
if ( inputSorted.Length % 2 == 1 )
{
   output.Add( inputSorted[inputSorted.Length / 2] );
}