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:
    Code:
    '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:
    Code:
    If CallSub2(Data.Get(i), "CompareTo", pivotValue) <= 0 Then
    Usage example:
    Code:
    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(1100), Rnd(110))
         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.
     

    Attached Files:

    vecino, Dave O, koaunglay and 5 others like this.
Loading...
  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