To powinno być coś takiego:
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;
}
Zauważ użycie zmiennej ascending
zapisać "kierunek" tablicy. Został zainicjowany po raz pierwszy, gdy znaleziono dwa różne elementy.
Pamiętaj, że jeśli chcesz, możesz nawet zwrotu „kierunek” tablicy:
public static bool IsArraySorted(int[] numbers, out bool isAscending)
{
isAscending = true;
bool? ascending = null;
i wewnątrz if (ascending == null)
if (ascending == null)
{
ascending = ascending2;
isAscending = ascending2;
}
Jest to ogólny wersja na podstawie 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;
}
Uwaga na użycie bool first
/obsłużyć i - 1
(i fakt, że cykl for
w stanie „przeskok” pierwszego elementu)
Jeśli istnieją dwa continguus wartości z tym samym numerem co jest pożądane zachowanie? –
Korzystanie z funkcji powrotu kończy działanie, podczas gdy prawdopodobnie chcesz zapętlić całą kolekcję przed zwróceniem czegokolwiek ... –
@Bartdude Myślę, że jest to zgodne z projektem - jeśli już odkryłeś, że nie jest posortowane, nie musisz sprawdzać reszty tablicy :-) –