C# sorting arrays in ascending and descending order

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

    Where is my answer? I wrote it about an hour ago:

    public enum SortType
    {
         unsorted   = 0,
         ascending  = 1,
         descending = 2
    }
    
    public static SortType IsArraySorted(int[] numbers)
    {
        bool ascSorted = true;
        bool descSorted = true;
    
        List asc = new List(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);
    }
    

    Example:

    enter image description here

提交回复
热议问题