IsSorted MethodDetermine if an array is already sorted by implementing an IsSorted method.
C#
IsSorted, array. A 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.
Method details. 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.
Sort
Required output. 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
An example. 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.
CompareTo
for
Info IsSorted checks that the int array specified is sorted in ascending order.
Also 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[] arr) { for (int i = 1; i < arr.Length; i++) { if (arr[i - 1] > arr[i]) { return false; } } return true; } /// <summary> /// Determines if string array is sorted from A -> Z /// </summary> public static bool IsSorted(string[] arr) { for (int i = 1; i < arr.Length; i++) { if (arr[i - 1].CompareTo(arr[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[] arr) { for (int i = arr.Length - 2; i >= 0; i--) { if (arr[i] < arr[i + 1]) { return false; } } return true; } /// <summary> /// Determines if string array is sorted from Z -> A /// </summary> public static bool IsSortedDescending(string[] arr) { for (int i = arr.Length - 2; i >= 0; i--) { if (arr[i].CompareTo(arr[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
Notes, descending. The IsSortedDescending method checks that the argument array is sorted from high to low—this is descending order. We must implement special "descending" loops.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.