tList.Sort()

BlitzMax Forums/BlitzMax Programming/tList.Sort()

GfK(Posted 2006) [#1]
Hello.

Assuming the following:
[code]Type MyType
Field Name:string
Field Age:Byte
End Type[code]
...how do I sort the tList by Age? Am I going to have to write my own Sort code, or is there a way to get the Sort() method to do it?

The documentation may as well be written in Japanese.
Method Sort( ascending=True,compareFunc( o1:Object,o2:Object )=CompareObjects )
Description Sort a list in either ascending (default) or decending order.
Information User types should implement a Compare method in order to be sorted.




kfprimm(Posted 2006) [#2]
here's an example...
SuperStrict

Local guy1:MyType=New MyType
guy1.Name="Bob"
guy1.age=50

Local guy2:MyType=New MyType
guy2.Name="Billy"
guy2.age=2

Local guy3:MyType=New MyType
guy3.Name="Joe"
guy3.age=80

ListAddLast MyType.list,guy1
ListAddLast MyType.list,guy2
ListAddLast MyType.list,guy3

Print "List before being sorted:"
Print ""
For Local guy:MyType=EachIn MyType.list
	Print guy.Name+" is "+guy.age+" year(s) old"
Next
MyType.Sort()
Print ""
Print "List before after being sorted:"
Print ""
For Local guy:MyType=EachIn MyType.list
	Print guy.Name+" is "+guy.age+" year(s) old"
Next

Type MyType
	Global list:TList=CreateList()
	Field Name:String
	Field Age:Byte
	
	Function Sort()
		SortList(list,True,CompareAge)
	End Function
	
	Function CompareAge:Int(o1:Object,o2:Object)
		If MyType(o1).age>MyType(o2).age Return 1
		Return 0
	End Function	
End Type



TomToad(Posted 2006) [#3]
There are two ways.
1) Override the Compare method, return -1 if self < object, +1 if self > object or 0 if they are equal. However, this creates problems with TList, so with version 1.20, method #2 was introduced. :)
2) create a function that takes two objects and return -1 if o1 < o2, +1 if o1 > o2, and 0 if they are equal.

Type MyType
	Field name:String
	Field age:Int
End Type

Local MyList:TList = CreateList()

For Local t = 0 To 10
	MyPerson:MyType = New MyType
	MyPerson.name = Chr(Rand(65,90))+Chr(Rand(65,90))+Chr(Rand(65,90))
	MyPerson.age = Rand(18,65)
	ListAddLast(MyList,MyPerson)
Next

Print "unsorted...."
For MyPerson:MyType = EachIn MyList
	Print "Name: "+MyPerson.name+" Age: "+MyPerson.age
Next

SortList(MyList,True,MySortFunction)
Print "~nSorted...."
For MyPerson:MyType = EachIn MyList
	Print "Name: "+MyPerson.name+" Age: "+MyPerson.age
Next

Function MySortFunction:Int(o1:Object, o2:Object)
	Return MyType(o1).age-MyType(o2).age
End Function
	



sswift(Posted 2006) [#4]
Why didn't they just fix TList so it uses the compare method CORRECTLY? It seems stupid to add kludges to the language just so it is backwards compatible. Especially when the help file probably still talks about the compare method being used for sorting the list.


Grisu(Posted 2006) [#5]
There's no fun with no bugs... ;)


TomToad(Posted 2006) [#6]
There's no fun with no bugs... ;)

I wrote a program with rats :)