Das (wie ich finde) beste Beispiel ist die Funktion bzw. das Macro CustomSortList():
Code: Alles auswählen
Prototype.i CustomSortListComparisonCallback(*Element1, *Element2)
Structure CustomSortList
Callback.CustomSortListComparisonCallback
Quit.i
*Element
EndStructure
Threaded CustomSortList.CustomSortList
Macro CustomSortList(LinkedList, ComparisonCallback)
CustomSortList\Callback = ComparisonCallback
Repeat
CustomSortList\Quit = #True
ForEach LinkedList
CustomSortList\Element = @LinkedList
While NextElement(LinkedList)
If CustomSortList\Callback(CustomSortList\Element, @LinkedList)
SwapElements(LinkedList, CustomSortList\Element, @LinkedList)
CustomSortList\Quit = #False
EndIf
Wend
ChangeCurrentElement(LinkedList, CustomSortList\Element)
Next
Until CustomSortList\Quit
EndMacro
Mit diesem Macro kann man eine beliebige LinkedList mit einer beliebigen Vergleichsfunktion sortieren lassen.
Hier zwei Beispiele, wie man Zahlen (ohne berücksichtigung des Vorzeichens) sortieren kann und eine strukturierte Liste zB nach Namen und zusätzlich nach Vorname sortieren kann:
Code: Alles auswählen
;- Beispiel 1
NewList Zahlen.i()
Define I.i
Procedure SortWithoutSign(*Integer1.Integer, *Integer2.Integer)
If Abs(*Integer1\i) > Abs(*Integer2\i)
ProcedureReturn #True
EndIf
EndProcedure
RandomSeed(1)
For I = 1 To 10
AddElement(Zahlen())
Zahlen() = Random(200)-100
Next
Debug "Unsortiert:"
ForEach Zahlen()
Debug Zahlen()
Next
Debug "Sortiert:"
CustomSortList(Zahlen(), @SortWithoutSign())
ForEach Zahlen()
Debug Zahlen()
Next
;- Beispiel 2
Structure Person
Name.s
Vorname.s
EndStructure
NewList Person.Person()
Define I.i
Procedure SortPerson(*Person1.Person, *Person2.Person)
If *Person1\Name > *Person2\Name
ProcedureReturn #True
ElseIf *Person1\Name = *Person2\Name And *Person1\Vorname > *Person2\Vorname
ProcedureReturn #True
EndIf
EndProcedure
RandomSeed(1)
For I = 1 To 10
AddElement(Person())
Person()\Name = Chr(Random(26)+65)
Person()\Vorname = Chr(Random(26)+65)
Next
Debug "Unsortiert:"
ForEach Person()
Debug Person()\Name+", "+Person()\Vorname
Next
Debug "Sortiert:"
CustomSortList(Person(), @SortPerson())
ForEach Person()
Debug Person()\Name+", "+Person()\Vorname
Next
Unsortiert:
45
-64
22
83
-100
-76
1
-42
-15
68
Sortiert:
1
-15
22
-42
45
-64
68
-76
83
-100
Unsortiert:
T, E
Q, Y
A, D
N, H
L, W
T, T
Q, I
Y, B
C, E
C, C
Sortiert:
A, D
C, C
C, E
L, W
N, H
Q, I
Q, Y
T, E
T, T
Y, B