# Sort Dot-Notation Numbers (e.g. 2.1.2)

Any good suggestion how to sort a tree list with dot-notation numbers?
For examples (sorted):
1
1.1
1.1.1
1.1.2
1.2
2
2.1
2.1.1
2.1.2.1
2.1.2.2

My ideas:
-Make an 2d-array with splited numbers and loop trough
-Remove dots, search for biggest number and add zeros to the rest (1000,1100,1110,1200,2000,2100,2110,…) and sort it

A simple solution could be to use simple bubble sorting and sort them alphabetically as strings.

But the above will only word if the numbers never goes above 9.

Numbers can go above 9

Is there a limit to the depth of the numbers (e.g. in your example the maximum depth is 4)?

No, there is no limit. :-/

Something like this maybe:

``````  dim arr() as string = array("2.1.15.1", "1.1", "1.1.1", "1.2", "2", "2.1", "2.1.1", "2.1.9.2", "2.1.2.1", "2.1.2.2", "1", "1.1.2")

dim TmpArr() as String
dim tmpStr as string
dim i as integer

dim TmpSplit(-1) as String
for each tmpstr in arr
TmpSplit = Split(tmpStr, ".")
for i = 0 to UBound(TmpSplit)
TmpSplit(i) = Format(val(TmpSplit(i)), "00000000000")
next
TmpArr.Append join(TmpSplit, ".")
next

TmpArr.SortWith(Arr)``````

Here is Alain’s algorithm wrapped into a reusable method…

``````Sub SortNumbers(ByRef numberArr() As String)
dim TmpArr() as String
dim tmpStr as string
dim i as integer

dim TmpSplit(-1) as String
for each tmpstr in numberArr
TmpSplit = Split(tmpStr, ".")
for i = 0 to UBound(TmpSplit)
TmpSplit(i) = Format(val(TmpSplit(i)), "00000000000")
next
TmpArr.Append join(TmpSplit, ".")
next

numberArr.SortWith(TmpArr)
End Sub``````

Hi Alwyn, I think the last line should be TmpArr.SortWith(numberArr). (We’re sorting the newly created tmpArr and sort the original one accordingly).

Hi Alain,

I’m getting the correct results when using numberArr.SortWith(TmpArr)? Here is a link to the test harness that I used for testing…

Test Harness

The sort method is invoke as follow…

``SortNumbers(numberArr)``

…passing the array using ByRef.

Yes, for your example it works, as all you do is sort the original array. But try it with this:

``````2.1
2.1.1
2.1.2.2
1
1.1.1
2.1.15.1  <-
2.1.9.1 <-
1.2
2
2.1.2.1
1.1
1.1.2``````

Now it’s not sorted correctly

``````1
1.1
1.1.1
1.1.2
1.2
2
2.1
2.1.1
2.1.15.1  <-
2.1.2.1
2.1.2.2
2.1.9.1 <-``````

If you change the code to TmpArr.SortWith(numberArr) you get:

``````1
1.1
1.1.1
1.1.2
1.2
2
2.1
2.1.1
2.1.2.1
2.1.2.2
2.1.9.1  <-
2.1.15.1 <-``````

My bad… thanks for pointing out the bug… here is the fixed method…

``````Sub SortNumbers(ByRef numberArr() As String)
dim TmpArr() as String
dim tmpStr as string
dim i as integer

dim TmpSplit(-1) as String
for each tmpstr in numberArr
TmpSplit = Split(tmpStr, ".")
for i = 0 to UBound(TmpSplit)
TmpSplit(i) = Format(val(TmpSplit(i)), "00000000000")
next
TmpArr.Append join(TmpSplit, ".")
next

TmpArr.SortWith(numberArr)

End Sub``````

You’re welcome

Works perfect! Thank you!