Android Question How to sort a string?

tsteward

Well-Known Member
Licensed User
Longtime User
I'm sure this has been covered but my searching has yielded no result.
I need to sort a string. In this app the string will hold 1, 2, 3 or 4 characters. The characters will each be numerals.
so "423" or "4132" or "32" they will only ever be 1, 2, 3 or 4 and no digit will ever appear twice. I just need each string to be sorted from lowest to highest.
 

Mahares

Expert
Licensed User
Longtime User
Are you looking for something like this. There may be a more efficient way:
B4X:
Dim strVar As String="4132"
Dim strNewVar As String
Dim MyList As List
MyList.Initialize
For i=0 To strVar.Length-1
  MyList.Add(strVar.SubString2(i,i+1))
Next
MyList.Sort(True)
For i=0 To MyList.Size-1
  strNewVar= strNewVar & MyList.Get(i)
Next
Msgbox(strNewVar,"") 'returns 1234
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
Better than I could manage and I'll use that thank you.:cool:
But if there is a better way please post :)
How about this one:

B4X:
    Dim str As String = "4132"
    Dim Swapped As Boolean
    Swapped = True
    Do While Swapped
        Swapped = False
        For i = 1 To str.Length-1
            If Asc(str.CharAt(i)) < Asc(str.CharAt(i-1)) Then
                str=str.SubString2(0,i-1)&str.SubString2(i,i+1)&str.SubString2(i-1,i)&str.SubString(i+1)
                Swapped = True
            End If
        Next
    Loop

    Log(str)

A simple bubble sort, it should be OK for 4 characters.
 
Last edited:
Upvote 0

tsteward

Well-Known Member
Licensed User
Longtime User
that is what I was trying to write but failed :mad:
I guess on such a small sort it probably doesn't matter which of the above methods I use as neither will add much in the way of overheads.

Thanks Guys
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
Apparently, according to wikipedia, a pigeon hole algorithm is most efficient for this kind of use something like:

B4X:
    Dim str As String = "1432"  
    Dim num As Int
    Dim PigeonHole(5) As Boolean
    For i = 0 To str.Length-1
        num = str.SubString2(i,i+1)
        PigeonHole(num)=True
    Next
    str=""
    For i = 1 To 4
        If PigeonHole(i) = True Then str=str&i
    Next
  
    Log(str)
 
Upvote 0
Top