choose a field type to sort a list

BlitzMax Forums/BlitzMax Beginners Area/choose a field type to sort a list

hub(Posted 2006) [#1]
Hi !

' pseudo code 
Type TPix
  field x : int
  field y : int
End type

Global Pixels_list = createlist()

Function Create:TPix (x,y)
	
	Local p:TPix = New TPix
	p.x = x
	p.y = y
	ListAddlast Pixels_list, p
	Return p
		
End Function


How to sort Pixels_list items by 'y' ascending ?
i don't understand how to use sortlist !
Thanks !


tonyg(Posted 2006) [#2]
Create a function, such as compare_y, which specifies what you want to sort against. Then, when you call sortlist, declare that function as the 'CompareFunc'.



JazzieB(Posted 2006) [#3]
EDIT: Should have looked at the above example a bit harder, as it has the Compare() Method in there!

There's a Compare() Method that you can build into your Types that Blitz will use to sort your type with the Sort() Method. Once you have the Compare() Method as part of your Type you can use yourList.Sort() to sort it.

This Compare() Method compares an object passed to it with the current one. You can then use whatever you want to decide which is the higher/lower of the two.

Here's an example.

Strict

Type TPerson
	Field name:String
	
	Global nameList:TList
	
	Function Create(p:String)
		If nameList=Null Then nameList=CreateList()
		Local newPerson:TPerson=New TPerson
		nameList.AddLast(newPerson)
		newPerson.name=p
	EndFunction
	
	Function ShowList()
		For Local i:TPerson=EachIn nameList
			Print "  "+i.name
		Next
	EndFunction
	
	Method Compare:Int(p:Object)
		Local n:TPerson=TPerson(p)
		If n Then
			If name.ToUpper() < n.name.ToUpper() Then
				Return -1
			ElseIf name.ToUpper() > n.name.ToUpper() Then
				Return 1
			Else
				Return 0
			EndIf
		Else
			Return 0
		EndIf
	EndMethod
EndType

RestoreData nameData

Local n:String
For Local i:Int=0 To 4
	ReadData n
	TPerson.Create(n)
Next

Print
Print "Before sorting..."
TPerson.ShowList

Print
Print "After sorting..."
TPerson.nameList.Sort
TPerson.ShowList

#nameData
DefData "Jay","Lisa","Shona","Mum","dad"


Sorry there's no comments, as it was just a quick program I put together to try and get my head around it. Hope it helps though.


hub(Posted 2006) [#4]
tony, JazzieB, many thanks for your code and explanations !!!


sswift(Posted 2006) [#5]
You do not want to modify the compare method, because that will mess up other functions for dealing with lists. I know the help file tells you to, but it's wrong. That's why the ability to pass a sort function to the sortlist command was created.