The Sorter class uses quick sort algorithm to sort a list of objects.
There are exactly three assumptions about the list items:
1. All the items in the list are of the same type (or each item can be compared with all other items).
2. The item's class has a sub named CompareTo and it follows the following contract:
3. You are free to use whichever comparison logic you like. However it must be consistent:
A > B means that B < A
A = B means that B = A
A < B means that B > A
The Sorter class code is not familiar with any implementation or type. It just calls the CompareTo method:
Usage example:
The classes are compatible with B4A, B4i and B4J.
There are exactly three assumptions about the list items:
1. All the items in the list are of the same type (or each item can be compared with all other items).
2. The item's class has a sub named CompareTo and it follows the following contract:
B4X:
'Returns -1 if this < other
'Returns 0 if equal
'Returns 1 if this > other
Public Sub CompareTo (Other As MyType) As Int
A > B means that B < A
A = B means that B = A
A < B means that B > A
The Sorter class code is not familiar with any implementation or type. It just calls the CompareTo method:
B4X:
If CallSub2(Data.Get(i), "CompareTo", pivotValue) <= 0 Then
Usage example:
B4X:
Sub Activity_Create(FirstTime As Boolean)
If FirstTime Then
sort.Initialize
End If
Dim transactions As List
transactions.Initialize
For i = 1 To 30
Dim t As Transaction
'Price, Amount
t.Initialize(Rnd(1, 100), Rnd(1, 10))
transactions.Add(t)
Next
'sorts the transactions based on Price * Amount
sort.SortList(transactions)
For Each t As Transaction In transactions
Log(t)
Next
Dim gibb As List
gibb.Initialize
For i = 1 To 30
Dim g As Gibberish
g.Initialize
gibb.Add(g)
Next
'Sorts the Gibberish items based on the text length
sort.SortList(gibb)
For Each g As Gibberish In gibb
Log(g)
Next
End Sub
The classes are compatible with B4A, B4i and B4J.