IsSorted
, arrayIs a VB.NET array of Strings or Integers sorted? By doing a pass through the elements in the array, we can avoid sorting the array again.
With Integers, we can compare elements directly. But with strings, we must use the CompareTo
Function to determine the correct sorting order.
This program introduces 2 different IsSorted
methods, as well as 2 IsSortedDescending
methods. These all loop through array elements and return a Boolean
.
CompareTo
to the one after it, and check the result against 0.Module Module1 Function IsSorted(array as Integer()) As Boolean For i = 1 To array.Length - 1 If array(i - 1) > array(i) Return False End If Next Return True End Function Function IsSorted(array as String()) As Boolean For i = 1 To array.Length - 1 If array(i - 1).CompareTo(array(i)) > 0 Return False End If Next Return True End Function Function IsSortedDescending(array As Integer()) As Boolean For i = array.Length - 2 To 0 Step -1 If array(i) < array(i + 1) Return False End If Next Return True End Function Function IsSortedDescending(array As String()) As Boolean For i = array.Length - 2 To 0 Step -1 If array(i).CompareTo(array(i + 1)) < 0 Return False End If Next Return True End Function Sub Main() ' Test the IsSorted functions. Dim sortedInts() = { 1, 4, 6, 8 } Console.WriteLine(IsSorted(sortedInts)) Dim sortedStrings() = { "ant", "bird", "zoo" } Console.WriteLine(IsSorted(sortedStrings)) Dim unsortedInts() = { 500, 100, 200 } Console.WriteLine(IsSorted(unsortedInts)) Dim unsortedStrings() = { "x", "a", "z", "b" } Console.WriteLine(IsSorted(unsortedStrings)) End Sub End ModuleTrue True False False
While IsSorted
can be used a performance optimization to avoid sorting, it can also be used in situations where we just want to know if the elements are sorted for some reason.