C#按升序和降序排序数组

C#按升序和降序排序数组,c#,arrays,sorting,C#,Arrays,Sorting,如果数组(数字)的元素按升序或降序排序,我在编写返回true的方法时遇到问题,如果它们不按任何排序顺序,则返回false。如果数组是升序的,我可以返回正确的布尔值,但我不知道如何在相同的方法中检查降序。我目前有: public static bool IsArraySorted(int[] numbers) { for (int i = 1; i < numbers.Length; i++) { if (numbers[i - 1] > numbers

如果数组(数字)的元素按升序或降序排序,我在编写返回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;
}
publicstaticboolsarraysorted(int[]数字)
{
for(int i=1;i数字[i])
返回false;
}
返回true;
}
是否有人能够提供有关如何检查排序降序数组的帮助?干杯

公共静态布尔校验(最终int[]数据)
public static boolean checkSortedness(final int[] data) 
{
    for (int i = 1; i < data.length; i++) 
    {
        if (data[i-1] > data[i]) {
            return false;
        }
    }
    return true;
}
{ 对于(int i=1;i数据[i]){ 返回false; } } 返回true; }
它应该类似于:

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;
}
if(升序==null)

这是基于
IEnumerable
的通用版本:

public static bool已排序(IEnumerable source,out bool isAscending,Comparer-Comparer=null)
{
Isascing=正确;
if(比较器==null)
{
comparer=comparer.Default;
}
bool first=true;
TSource-previous=默认值(TSource);
bool?升序=空;
foreach(t源中的源电流)
{
如果(!第一个)
{
int cmp=比较器。比较(上一个,当前);
如果(cmp!=0)
{
bool上升2=cmp<0;
if(升序==null)
{
上升=上升2;
i上升=上升2;
}
else if(升序.Value!=升序2)
{
返回false;
}
}
}
第一个=假;
先前=当前;
}
返回true;
}
请注意,使用
bool first
/
TSource previous
来处理
i-1
(以及
for
循环能够“跳过”第一个元素的事实)

使用Linq-

public static bool IsArraySorted(int[] numbers)
{
    var orderedAsc = numbers.OrderBy(a => a);
    var orderedDes = numbers.OrderByDescending(a => a);

    bool isSorted = numbers.SequenceEqual(orderedAsc) ||
                    numbers.SequenceEqual(orderedDes);
    return isSorted;
}

这将使用一个循环来测试两种情况:

public static bool IsSorted<T>(IEnumerable<T> items, Comparer<T> comparer = null)
{
    if (items == null) throw new ArgumentNullException("items");
    if (!items.Skip(1).Any()) return true;  // only one item

    if (comparer == null) comparer = Comparer<T>.Default;
    bool ascendingOrder = true; bool descendingOrder = true;

    T last = items.First();
    foreach (T current in items.Skip(1))
    {
        int diff = comparer.Compare(last, current);
        if (diff > 0)
        {
            ascendingOrder = false;
        }
        if (diff < 0)
        {
            descendingOrder = false;
        }
        last = current;
        if(!ascendingOrder && !descendingOrder) return false;
    }
    return (ascendingOrder || descendingOrder);
}
如果将其作为扩展方法,则可以将其用于任何类型:

bool ordered = new[]{"A", "B", "C"}.IsSorted();

我的答案在哪里?我大约一小时前写的:

public enum SortType
{
     unsorted   = 0,
     ascending  = 1,
     descending = 2
}

public static SortType IsArraySorted(int[] numbers)
{
    bool ascSorted = true;
    bool descSorted = true;

    List<int> asc = new List<int>(numbers);            

    asc.Sort();

    for (int i = 0; i < asc.Count; i++)
    {
        if (numbers[i] != asc[i]) ascSorted = false;
        if (numbers[asc.Count - 1 - i] != asc[i]) descSorted = false;
    }

    return ascSorted ? SortType.ascending : (descSorted? SortType.descending : SortType.unsorted);
}
公共枚举排序类型
{
未排序=0,
升序=1,
下降=2
}
公共静态排序类型IsArraySorted(int[]数字)
{
bool=true;
bool=true;
列表asc=新列表(编号);
asc.Sort();
对于(int i=0;i
例如:


这看起来更像是一项学术任务,而不是一个实际问题。我想时不时地回到基本面并没有什么坏处:

public static bool IsSortedAscOrDesc(int[] arr)
{
    int last = arr.Length - 1;
    if (last < 1) return true;

    bool isSortedAsc = true;
    bool isSortedDesc = true;

    int i = 0;
    while (i < last && (isSortedAsc || isSortedDesc)) 
    {
        isSortedAsc &= (arr[i] <= arr[i + 1]);
        isSortedDesc &= (arr[i] >= arr[i + 1]);
        i++;
    }

    return isSortedAsc || isSortedDesc;
}
publicstaticboolsortedascordesc(int[]arr)
{
int last=阵列长度-1;
if(last<1)返回true;
bool-isSortedAsc=真;
bool isSortedDesc=真;
int i=0;
而(i
一个包含2个(或更少)元素的数组被排序,
{0,0}被排序为asc&desc、{0,1}asc、{1,0}desc、{1,1}asc&desc。
可以使用一个循环,但分离案例似乎更快。 对于包含2个以上元素的数组,
如果第一个元素小于最后一个元素, 检查:a[i]0)a[i]=i--//a[511]=1; 控制台写入线(isSorted0(a)); var w=System.Diagnostics.Stopwatch.StartNew(); 对于(i=1000000;i>0;i--)为0(a); 控制台写入(w.ElapsedMilliseconds);Console.Read(); } 静态布尔值为0(int[]a)//267毫秒 { 如果(a.Length<3)返回true;int j=a.Length-1; 返回a[0]a[j]?减少(a):相同(a); } 静态布尔增量(int[]a) { int ai=a[0],i=1,j=a.长度; 而(i 简短的版本

    static bool isSorted(int[] a)
    {
        if (a.Length < 3) return true; int i = a.Length - 1, ai = a[i--];
        if (ai > a[0]) while (i >= 0 && ai >= (ai = a[i])) i--;
        else if (ai < a[0]) while (i >= 0 && ai <= (ai = a[i])) i--;
        else while (i >= 0 && ai == a[i]) i--; return i < 0;
    }
静态布尔值排序(int[]a)
{
如果(a.Length<3)返回true;int i=a.Length-1,ai=a[i--];
如果(ai>a[0]),而(i>=0&&ai>=(ai=a[i])i--;
else如果(ai=0&&ai=0&&ai==a[i])i--;返回i<0;
}

如果有两个连续值具有相同的数字,这是所需的行为?使用return退出函数,而您可能希望在返回任何内容之前循环整个集合…@Bartdude我认为这是出于设计-如果您已经发现它没有排序,不需要检查数组的其余部分:-)我可以只使用(number.Length/2)而不是查看完整的列表吗?@Amit
{1,2,3,-5}
如果不检查最后一个值,您将如何捕获顺序错误的
-5
?@xanatos,如果传入的数组长度为0或1,您将获得
OutOfRangeException
。您需要在方法顶部进行一些参数检查。@wyatterp否。
bool ordered = new[]{"A", "B", "C"}.IsSorted();
public enum SortType
{
     unsorted   = 0,
     ascending  = 1,
     descending = 2
}

public static SortType IsArraySorted(int[] numbers)
{
    bool ascSorted = true;
    bool descSorted = true;

    List<int> asc = new List<int>(numbers);            

    asc.Sort();

    for (int i = 0; i < asc.Count; i++)
    {
        if (numbers[i] != asc[i]) ascSorted = false;
        if (numbers[asc.Count - 1 - i] != asc[i]) descSorted = false;
    }

    return ascSorted ? SortType.ascending : (descSorted? SortType.descending : SortType.unsorted);
}
public static bool IsSortedAscOrDesc(int[] arr)
{
    int last = arr.Length - 1;
    if (last < 1) return true;

    bool isSortedAsc = true;
    bool isSortedDesc = true;

    int i = 0;
    while (i < last && (isSortedAsc || isSortedDesc)) 
    {
        isSortedAsc &= (arr[i] <= arr[i + 1]);
        isSortedDesc &= (arr[i] >= arr[i + 1]);
        i++;
    }

    return isSortedAsc || isSortedDesc;
}
using System;
class Program
{
    static void Main()
    {
        int i = 512; int[] a = new int[i--]; while (i > 0) a[i] = i--; //a[511] = 1;
        Console.WriteLine(isSorted0(a));
        var w = System.Diagnostics.Stopwatch.StartNew();
        for (i = 1000000; i > 0; i--) isSorted0(a);
        Console.Write(w.ElapsedMilliseconds); Console.Read();
    }

    static bool isSorted0(int[] a)  // 267 ms
    {
        if (a.Length < 3) return true; int j = a.Length - 1;
        return a[0] < a[j] ? incr(a) : a[0] > a[j] ? decr(a) : same(a);
    }
    static bool incr(int[] a)
    {
        int ai = a[0], i = 1, j = a.Length;
        while (i < j && ai <= (ai = a[i])) i++; return i == j;
    }
    static bool decr(int[] a)
    {
        int ai = a[0], i = 1, j = a.Length;
        while (i < j && ai >= (ai = a[i])) i++; return i == j;
    }
    static bool same(int[] a)
    {
        int ai = a[0], i = 1, j = a.Length - 1;
        while (i < j && ai == a[i]) i++; return i == j;
    }

    static bool isSorted1(int[] numbers)  // 912 ms  accepted answer
    {
        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;
    }
}
    static bool isSorted(int[] a)
    {
        if (a.Length < 3) return true; int i = a.Length - 1, ai = a[i--];
        if (ai > a[0]) while (i >= 0 && ai >= (ai = a[i])) i--;
        else if (ai < a[0]) while (i >= 0 && ai <= (ai = a[i])) i--;
        else while (i >= 0 && ai == a[i]) i--; return i < 0;
    }