C# sorting arrays in ascending and descending order

前端 未结 7 1056
感动是毒
感动是毒 2020-12-19 02:27

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

相关标签:
7条回答
  • 2020-12-19 03:23

    This uses one loop to test both cases:

    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);
    }
    

    usage:

    int[] ints = { 1, 2, 3, 4, 5, 6 };
    bool isOrderedAsc = IsSorted(ints); // true
    bool isOrderedDesc = IsSorted(ints.Reverse()); //true
    

    If you make it an extension method you can use it with any type:

    bool ordered = new[]{"A", "B", "C"}.IsSorted();
    
    0 讨论(0)
提交回复
热议问题