C# sorting arrays in ascending and descending order

前端 未结 7 1081
感动是毒
感动是毒 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:09

    It should be something like:

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

    Note the use of the ascending variable to save the "direction" of the array. It is initialized the first time two elements that are different are found.

    Note that if you want, you can even return the "direction" of the array:

    public static bool IsArraySorted(int[] numbers, out bool isAscending)
    {
        isAscending = true;
        bool? ascending = null;
    

    and inside the if (ascending == null)

    if (ascending == null)
    {
        ascending = ascending2;
        isAscending = ascending2;
    }
    

    This is a generic version based on IEnumerable:

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

    Note the use of bool first/TSource previous to handle the i - 1 (and the fact that the for cycle was able to "skip" the first element)

提交回复
热议问题