C# sorting arrays in ascending and descending order -


i'm having trouble writing method returns true if elements of array (numbers) in sorted order, ascending or descending, , false, if not in sorted order. can return correct boolean value if array ascending not know how check descending order in same method. have:

public static bool isarraysorted(int[] numbers)     {       (int = 1; < numbers.length; i++)         {             if (numbers[i - 1] > numbers[i])             {                 return false;             }          }         return true;     } 

anyone able offer on how check sorted descending array well? cheers!

it should like:

public static bool isarraysorted(int[] numbers) {     bool? ascending = null;      (int = 1; < 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 use of ascending variable save "direction" of array. initialized first time 2 elements different found.

note if want, can return "direction" of array:

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

and inside if (ascending == null)

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

this generic version based on 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; } 

note use of bool first/tsource previous handle i - 1 (and fact for cycle able "skip" first element)


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

c# - Exception when attempting to modify Dictionary -