它应该是这样的:
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;
}
注意使用升序变量来保存数组的“方向”.它是在第一次找到两个不同的元素时初始化的.
请注意,如果需要,您甚至可以返回数组的“方向”:
public static bool IsArraySorted(int[] numbers, out bool isAscending)
{
isAscending = true;
bool? ascending = null;
在if内(升序== null)
if (ascending == null)
{
ascending = ascending2;
isAscending = ascending2;
}
这是基于IEnumerable< TSource>的通用版本:
public static bool IsSorted(IEnumerable source, out bool isAscending, Comparer comparer = null)
{
isAscending = true;
if (comparer == null)
{
comparer = Comparer.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之前处理i – 1(以及for循环能够“跳过”第一个元素的事实)