Sorting a Type
BlitzMax Forums/BlitzMax Beginners Area/Sorting a Type
| ||
Say I have an array of Types, ie:Type blahType 'define the class Field x, y EndType Local array:blahType[21] 'set array memory For Local a = 0 To 20 'initialize slots array[a] = New blahType array[a].x = Rand(100) array[a].y = Rand(100) Print array[a].x+" "+array[a].y 'print what we've got Next array.sort 'sort damn you! (Of course this is too vague) Print For a = 0 To 20 'show results Print array[a].x+" "+array[a].y Next As you can see if you run this, Array.sort doesn't seem to sort Types at all when I address the type so vaguely. How would I go about sorting an array of Types by one of their internal values? Say I want to sort the array by the value of Array[].x [edit] I should mention, I'm trying to get arrays to work before I go with a List because I'm using this to sort the z positions of sprites in a graphic engine. I need speed! |
| ||
BlitzMax won't magically guess how you want to sort it. When sorting objects, it relies on the 'Compare' method to be able to give the relative order of 2 objects. You need to define this method.Something like:Type blahType 'define the class Field x, y Method Compare%(other:Object) Local t:blahType = blahType(other) If t = Null Then ' Not of the right type, fallback on default comparison Return Super.Compare(other) Else ' OK, let's compare them, first base on x, then y Local diff% = x - t.x If x = 0 Then diff = y - t.y EndIf Return diff EndIf End Method EndType |
| ||
Ok, I understand. That would definately work, but now I would have to write a quicksort algorithm myself, huh. *deep breath* Oh boy. |
| ||
Why so? 'Compare' is a method that the built-in sorting will call, it's that you need to define. |
| ||
Handy. The way that Compare works with Sort is kinda obscure in the docs; thanks for making it clear, Koriolis: Unsorted: 42 22 70 15 58 18 77 37 46 59 Sorted: 15 18 22 37 42 46 58 59 70 77 |
| ||
Well this is great news! Thanks guys. |