打印最小的值然后最高值



输入

[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#?

中实现此目标

另一个解决方案:

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

如果您对基于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是奇数)。

我看不到这与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] );
}

相关内容

最新更新