C# Sorted Array Test Method

Sorted letters: A through Z

You want to determine if an array you have is already sorted, ascending or descending. This is useful when accepting input that needs to be presorted, or for using certain algorithms. Apply this to int[] and string[] arrays.

Example arrays and IsSorted result

Array example: 1, 4, 6, 8
IsSorted:      True

Array example: 5, 2, 7, 6
IsSorted:      False

Array example: cat, man, zebra
IsSorted:      True

Array example: soda, pop, coke, tonic
IsSorted:      False

Test sorted arrays

When determining if an array is already sorted, you could call Sort on a copy of the array and then compare both arrays for equality. However, this is much slower than simply iterating through the array and using CompareTo on each element. Here we see a static class that checks int[] and string[] arrays for presorted elements.

This C# example shows how to determine if an array is already sorted.

Program that tests sorted arrays [C#]

using System;

class Program
{
    static void Main()
    {
	int[] sortedInts = new int[]
	{
	    1,
	    4,
	    6,
	    8
	};
	int[] unsortedInts = new int[]
	{
	    5,
	    2,
	    7,
	    6
	};
	int[] reversedInts = new int[]
	{
	    9,
	    8,
	    5,
	    1
	};
	string[] sortedStrings = new string[]
	{
	    "cat",
	    "man",
	    "zebra"
	};
	string[] unsortedStrings = new string[]
	{
	    "soda",
	    "pop",
	    "coke",
	    "tonic"
	};
	string[] reversedStrings = new string[]
	{
	    "zebra",
	    "partridge",
	    "apple"
	};
	Console.WriteLine(SortTools.IsSorted(sortedInts));                // True
	Console.WriteLine(SortTools.IsSortedDescending(sortedInts));      // False
	Console.WriteLine(SortTools.IsSorted(unsortedInts));              // False
	Console.WriteLine(SortTools.IsSortedDescending(unsortedInts));    // False
	Console.WriteLine(SortTools.IsSorted(reversedInts));              // False
	Console.WriteLine(SortTools.IsSortedDescending(reversedInts));    // True
	Console.WriteLine(SortTools.IsSorted(sortedStrings));             // True
	Console.WriteLine(SortTools.IsSortedDescending(sortedStrings));   // False
	Console.WriteLine(SortTools.IsSorted(unsortedStrings));           // False
	Console.WriteLine(SortTools.IsSortedDescending(unsortedStrings)); // False
	Console.WriteLine(SortTools.IsSorted(reversedStrings));           // False
	Console.WriteLine(SortTools.IsSortedDescending(reversedStrings)); // True
    }
}

/// <summary>
/// Methods for determining if arrays are sorted.
/// </summary>
public static class SortTools
{
    /// <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;
    }
}

Output

True
False
False
False
False
True
True
False
False
False
False
True
Array elements

Description of Main() method. The first part of the code above is the Main method, which tests the SortTools static class for accuracy. It declares six arrays, three for ints and three for strings. Each trio contains one ascending array, one unsorted array, and one descending array.

Descending and ascending. Recall that the word descending means "big to little", meaning 3, 2, 1 for ints and "z, y, x" for strings. Usually ascending sort is the default.

SortTools class. This is a public static class that you can put in an external file, called "SortTools.cs". You can access the member methods in this class with dot notation, as shown in Main.

IsSorted(int[]) method. This method checks that the int array specified is sorted in ascending order. It loops through the elements, starting at the second element. It compares each next element to the previous element using the > operator. It returns true or false.

IsSorted(string[]) method. This method works the same as its int equivalent. It calls CompareTo on strings, which returns 1 if the first string is "bigger", or -1 if the first string is "smaller." We use > 0 to make sure each successive string is bigger.

IsSortedDescending(int[]) method. This method works the same as IsSorted(int[]) but checks that the array is sorted from high to low, descending order.

IsSortedDescending(string[]) method. This method works the same as IsSortedDescending(string[]) but checks that the array is sorted from "biggest" to "smallest", descending order. You could implement the descending methods by looping either way.

Summary

The C# programming language

We saw some useful methods for determining if arrays are already sorted. They are fast, with optimal time complexity. No extra memory is allocated. You could adapt the approach in these methods to char[] or object[] arrays as well, or compare other attributes in the methods. It may be possible to develop a generic method, but that wouldn't enhance many usages. Extension methods could be used as well, but I feel they offer no advantage here.

Sort Examples
.NET