Sorting any field

BlitzMax Forums/BlitzMax Beginners Area/Sorting any field

tonyg(Posted 2006) [#1]
I realise you can use compare method to sort on a particular field.
However, I can't work out how to sort on ANY field.
For example, if I have a type with X and Y fields how can I use sortlist with compare override but specify which field out of X and Y I want sorted?


fredborg(Posted 2006) [#2]
Type Bob
  Field X,Y
  Field SortUsingY

  Method Compare(other:Object)
    If Bob(other)
      If SortUsingY
        Return Sgn(Y - Bob(other).Y)
      Else
        Return Sgn(X - Bob(other).X)
      EndIf
    EndIf
    Return -1
  EndMethod
EndType
Or something like that. It's probably better to have a global variable controlling which parameter to use, instead of one for each type instance.


tonyg(Posted 2006) [#3]
I went with the global variable as a quick solution.
What if the compare is against either an int or a string field?
What would the method return?
<EDIT> Ignore me. I'm being a muppet.


Eric(Posted 2006) [#4]
Lets say I have a List of this Type....
Type Unit
     Field X:Float,Y:Float
     Field Number:Int

     Method New()
          Number=Rand(1000)
          ListAddLast UnitList,Self
     End Method
End Type

How Can I Use Sort to Sort this list Using the Number Field. I want to go from Low to High.

Regards,
Eric


tonyg(Posted 2006) [#5]
Type Unit
     Global unitlist:Tlist=CreateList()
     Field X:Float,Y:Float
     Field Number:Int

     Method New()
          Number=Rand(1000)
          ListAddLast UnitList,Self
     End Method
     Method compare(myobject:Object)
          s:Unit = Unit(myobject)
          If Not s Then Return 1
          Return number - s.number
     End Method
End Type
SeedRnd MilliSecs()
For x = 1 To 100
  my:Unit = New unit
Next
   
SortList unit.unitlist
   
   ' Check to see if it is sorted correctly
For s:unit = EachIn unit.unitlist
    Print s.number
Next