https://www.javatpoint.com/tim-sort

to B4A code:

B4X:

```
Sub TestTimSort
Dim i As Int
Dim iSize As Int = 20
Dim arrInt(iSize) As Int
For i = 0 To iSize - 1
arrInt(i) = Rnd(0, 100)
Next
TimSort(arrInt, arrInt.Length)
For i = 0 To iSize - 1
Log(i & " - " & arrInt(i))
Next
End Sub
Sub TimSort(arrInt() As Int, n As Int)
Dim i As Int
Dim lSize As Int
Dim lBegin As Int
Dim lEnd As Int
Dim lMid As Int
For i = 0 To n - 1
TimInsertion(arrInt, i, Min(i + 31, n - 1))
i = i + iConstRun
Next
For lSize = iConstRun To n - 1
For lBegin = 0 To n - 1
lMid = lBegin + lSize - 1
lEnd = Min(lBegin + 2 * lSize - 1, n - 1)
TimMerge(arrInt, lBegin, lMid, lEnd)
lBegin = lBegin + (2 * lSize)
Next
lSize = lSize * 2
Next
End Sub
Sub TimInsertion(arrInt() As Int, lBegin As Int, lEnd As Int)
Dim i As Int
Dim j As Int
Dim lTemp As Int
For i = lBegin + 1 To lEnd
lTemp = arrInt(i)
j = i - 1
Do While CheckWhile(j, lBegin, arrInt, lTemp)
arrInt(j + 1) = arrInt(j)
j = j - 1
Loop
arrInt(j + 1) = lTemp
Next
End Sub
Sub CheckWhile(j As Int, lBegin As Int, arrInt() As Int, lTemp As Int) As Boolean
If j < 0 Then
Return False
End If
If j >= lBegin Then
If arrInt(j) > lTemp Then
Return True
End If
End If
Return False
End Sub
Sub TimMerge(arrInt() As Int, lLeft As Int, lMid As Int, lRight As Int)
Dim i As Int
Dim j As Int
Dim k As Int
Dim Len1 As Int
Dim Len2 As Int
Len1 = lMid - lLeft + 1
Len2 = lRight - lMid
Dim arrBegin(Len1) As Int
Dim arrEnd(Len2) As Int
For i = 0 To Len1 - 1
arrBegin(i) = arrInt(lLeft + i)
Next
For i = 0 To Len2 - 1
arrEnd(i) = arrInt(lMid + 1 + i)
Next
i = 0
j = 0
k = lLeft
Do While i < Len1 And j < Len2
If arrBegin(i) <= arrEnd(j) Then
arrInt(k) = arrBegin(i)
i = i + 1
Else
arrInt(k) = arrEnd(j) '<<<<< goes wrong here, too low values go to the array!
j = j + 1
End If
k = k + 1
Loop
Do While i < Len1
arrInt(k) = arrBegin(i)
k = k + 1
i = i + 1
Loop
Do While j < Len2
arrInt(k) = arrEnd(j)
k = k + 1
j = j + 1
Loop
End Sub
```

It works fine with arrays up to about 35 items, but above that it goes wrong as items

appear unsorted. It goes wrong in the TimMerge Sub as shown in the comment code comment.

Does anybody on this list understand C well enough to see why this B4A code doesn't work?

RBS