Android Tutorial [B4X][OOP] Generic Sorter

Discussion in 'Tutorials & Examples' started by Erel, Dec 21, 2016.

  1. Erel

    Erel Administrator Staff Member Licensed User

    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:
    'Returns -1 if this < other
    'Returns 0 if equal
    'Returns 1 if this > other
    Public Sub CompareTo (Other As MyType) As Int
    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:
    If CallSub2(Data.Get(i), "CompareTo", pivotValue) <= 0 Then
    Usage example:
    Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
    End If
    Dim transactions As List
    For i = 1 To 30
    Dim t As Transaction
    'Price, Amount
         t.Initialize(Rnd(1100), Rnd(110))
    'sorts the transactions based on Price * Amount
    For Each t As Transaction In transactions
    Dim gibb As List
    For i = 1 To 30
    Dim g As Gibberish
    'Sorts the Gibberish items based on the text length
    For Each g As Gibberish In gibb
    End Sub
    The classes are compatible with B4A, B4i and B4J.

    Attached Files:

    vecino, Dave O, koaunglay and 5 others like this.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice