Home
VB.NET
Array IsSorted Function
This page was last reviewed on Feb 13, 2024.
Dot Net Perls
IsSorted, array. Is 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.
CompareTo
Example. This program introduces 2 different IsSorted methods, as well as 2 IsSortedDescending methods. These all loop through array elements and return a Boolean.
Note For Integer arrays, we can compare each element to the one after it. This verifies the ordering.
Note 2 For Strings, we must test each element with CompareTo to the one after it, and check the result against 0.
Result When the arrays are sorted, these methods will return True, and False otherwise.
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 Module
True True False False
Summary. 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.
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.
This page was last updated on Feb 13, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.