C#升序和降序排序数组 [英] C# sorting arrays in ascending and descending order
问题描述
我很难编写一个方法,如果数组(数字)的元素按升序或降序排序,则返回true;如果数组的元素不按任何排序,则返回false.如果数组是升序的,我可以返回正确的布尔值,但是我不知道如何在同一方法中检查降序.我目前有:
I'm having trouble writing a method that returns true if the elements of an array (numbers) are in sorted order, ascending or descending, and false, if they are not in any sorted order. I can return a correct boolean value if the array is ascending but i do not know how to check for descending order as well in the same method. I currently have:
public static bool IsArraySorted(int[] numbers)
{
for (int i = 1; i < numbers.Length; i++)
{
if (numbers[i - 1] > numbers[i])
return false;
}
return true;
}
任何人都可以提供有关如何检查排序降序数组的帮助吗?干杯!
Anyone able to offer help on how to check for a sorted descending array as well? Cheers!
推荐答案
应该是这样的:
public static bool IsArraySorted(int[] numbers)
{
bool? ascending = null;
for (int i = 1; i < numbers.Length; i++)
{
if (numbers[i - 1] != numbers[i])
{
bool ascending2 = numbers[i - 1] < numbers[i];
if (ascending == null)
{
ascending = ascending2;
}
else if (ascending.Value != ascending2)
{
return false;
}
}
}
return true;
}
请注意使用ascending
变量来保存数组的方向".首次发现两个不同的元素时会对其进行初始化.
Note the use of the ascending
variable to save the "direction" of the array. It is initialized the first time two elements that are different are found.
请注意,如果需要,甚至可以返回数组的方向":
Note that if you want, you can even return the "direction" of the array:
public static bool IsArraySorted(int[] numbers, out bool isAscending)
{
isAscending = true;
bool? ascending = null;
和if (ascending == null)
if (ascending == null)
{
ascending = ascending2;
isAscending = ascending2;
}
这是基于IEnumerable<TSource>
的通用版本:
public static bool IsSorted<TSource>(IEnumerable<TSource> source, out bool isAscending, Comparer<TSource> comparer = null)
{
isAscending = true;
if (comparer == null)
{
comparer = Comparer<TSource>.Default;
}
bool first = true;
TSource previous = default(TSource);
bool? ascending = null;
foreach (TSource current in source)
{
if (!first)
{
int cmp = comparer.Compare(previous, current);
if (cmp != 0)
{
bool ascending2 = cmp < 0;
if (ascending == null)
{
ascending = ascending2;
isAscending = ascending2;
}
else if (ascending.Value != ascending2)
{
return false;
}
}
}
first = false;
previous = current;
}
return true;
}
请注意使用bool first
/TSource previous
处理i - 1
(以及for
循环能够跳过"第一个元素的事实)
Note the use of bool first
/TSource previous
to handle the i - 1
(and the fact that the for
cycle was able to "skip" the first element)
这篇关于C#升序和降序排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!