我编写一个方法,如果数组(数字)的元素按排序顺序,升序或降序,则返回true,如果它们不是任何排序顺序,则返回false.如果数组是升序但我不知道如何在同一方法中检查降序,我可以返回正确的布尔值.我目前有:
public static bool IsArraySorted(int[] numbers)
{
for (int i = 1; i < numbers.Length; i++)
{
if (numbers[i - 1] > numbers[i])
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以提供有关如何检查已排序的降序数组的帮助吗?干杯!
它应该是这样的:
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;
}
Run Code Online (Sandbox Code Playgroud)
注意使用ascending变量来保存数组的"方向".它是在第一次找到两个不同的元素时初始化的.
请注意,如果需要,您甚至可以返回数组的"方向":
public static bool IsArraySorted(int[] numbers, out bool isAscending)
{
isAscending = true;
bool? ascending = null;
Run Code Online (Sandbox Code Playgroud)
在里面 if (ascending == null)
if (ascending == null)
{
ascending = ascending2;
isAscending = ascending2;
}
Run Code Online (Sandbox Code Playgroud)
这是基于以下内容的通用版本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;
}
Run Code Online (Sandbox Code Playgroud)
注意使用bool first/ TSource previous来处理i - 1(以及for循环能够"跳过"第一个元素的事实)
| 归档时间: |
|
| 查看次数: |
9515 次 |
| 最近记录: |