IsSorted
, arrayA C# array may be already sorted. We can avoid sorting it again in this case. This is useful when accepting input that needs to be presorted, or for certain algorithms.
We develop "is sorted" methods for int
and string
arrays. Using a method that checks for sorted order avoids the cost of sorting the elements.
Consider an array that is already sorted, like an int
array that contains the elements 1, 2, 4 and 8. IsSorted
must return true here.
Array: 1, 2, 4, 8 Result: True
Let us examine the IsSorted
code. We loop over arrays, comparing adjacent elements for the correct ordering. This is a simple approach, but an effective one.
IsSorted
checks that the int
array specified is sorted in ascending order.IsSorted
with a string
array argument works the same as its int
equivalent. It calls CompareTo
on strings.using System; class Program { /// <summary> /// Determines if int array is sorted from 0 -> Max /// </summary> public static bool IsSorted(int[] array) { for (int i = 1; i < array.Length; i++) { if (array[i - 1] > array[i]) { return false; } } return true; } /// <summary> /// Determines if string array is sorted from A -> Z /// </summary> public static bool IsSorted(string[] array) { for (int i = 1; i < array.Length; i++) { if (array[i - 1].CompareTo(array[i]) > 0) // If previous is bigger, return false { return false; } } return true; } /// <summary> /// Determines if int array is sorted from Max -> 0 /// </summary> public static bool IsSortedDescending(int[] array) { for (int i = array.Length - 2; i >= 0; i--) { if (array[i] < array[i + 1]) { return false; } } return true; } /// <summary> /// Determines if string array is sorted from Z -> A /// </summary> public static bool IsSortedDescending(string[] array) { for (int i = array.Length - 2; i >= 0; i--) { if (array[i].CompareTo(array[i + 1]) < 0) // If previous is smaller, return false { return false; } } return true; } static void Main() { int[] sortedInts = new int[] { 1, 4, 6, 8 }; string[] unsortedStrings = new string[] { "soda", "pop", "coke", "tonic" }; // Test the methods. Console.WriteLine(IsSorted(sortedInts)); Console.WriteLine(IsSorted(unsortedStrings)); } }True False
The IsSortedDescending
method checks that the argument array is sorted from high to low—this is descending order. We must implement special "descending" loops.
We can determine if arrays are already sorted. These methods are fast. You could adapt the approach in these methods to char
or object arrays.