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.
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