1

say after using the Split function we have an array of strings like so ArrStr = ("this","is","a","random","phrase")

what I want to achieve is this:

  • first, ArrStr is sorted by the string length of the array items, i.e ArrStr = ("a","is","this","random","phrase") since len("a") = 1, len("is") = 2 ...etc

  • second, ArrStr then gets sorted again but this time alphabetically retaining the first sort by length, i.e ArrStr = ("a","is","this","phrase","random") ,the string "phrase" took the place of the string "random" since it starts with "p" and we all know that the letter "p" comes before the letter "r" in the English language.

during the sorting process, the text is considered case insensitive

any efficient ideas on how to achieve that?

0

1 Answer 1

3

Any sort algorithm will work - all you need to do is make your item comparisons based on your custom criteria:

Private Function SortCompare(one As String, two As String) As Boolean
    Select Case True
        Case Len(one) < Len(two)
            SortCompare = True
        Case Len(one) > Len(two)
            SortCompare = False
        Case Len(one) = Len(two)
            SortCompare = LCase$(one) < LCase$(two)
    End Select
End Function

For example, with a quicksort:

Public Sub CustomQuickSort(list() As String, first As Long, last As Long)
    Dim pivot As String
    Dim low As Long
    Dim high As Long

    low = first
    high = last
    pivot = list((first + last) \ 2)

    Do While low <= high
        Do While low < last And SortCompare(list(low), pivot)
            low = low + 1
        Loop
        Do While high > first And SortCompare(pivot, list(high))
            high = high - 1
        Loop
        If low <= high Then
            Dim swap As String
            swap = list(low)
            list(low) = list(high)
            list(high) = swap
            low = low + 1
            high = high - 1
        End If
    Loop

    If (first < high) Then CustomQuickSort list, first, high
    If (low < last) Then CustomQuickSort list, low, last
End Sub

Usage example:

Public Sub SampleCode()
    Dim sample() As String
    sample = Split("this,is,a,random,phrase", ",")
    CustomQuickSort sample, LBound(sample), UBound(sample)

    Dim i As Integer
    For i = LBound(sample) To UBound(sample)
        Debug.Print sample(i)
    Next i
End Sub

If you want this to sort descending, swap the SortCompare = True and SortCompare = False lines.

1
  • 1
    This algorithm was just what I needed. I had to add parenthesis in the pivot calculation so the addition happened before the division. I submitted an edit to the code.
    – Ben
    Commented Mar 14, 2019 at 1:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.