Hi all,
How would you go about sorting a list by multiple parameters? Taking a list of screen resolutions, for example, how would you sort first by width, then by height, then by depth? Sorting in ascending order, I would want the output to be something like this:
Width: 640
Height: 480
Depth: 16
Width: 640
Height: 480
Depth: 32
Width: 800
Height: 480
Depth: 16
Width: 800
Height: 480
Depth: 32
Width: 800
Height: 600
Depth: 16
Width: 800
Height: 600
Depth: 32
Width: 1024
Height: 600
Depth: 16
Width: 1024
Height: 600
Depth: 32
Width: 1024
Height: 768
Depth: 16
Width: 1024
Height: 768
Depth: 32
Width: 1280
Height: 720
Depth: 16
Width: 1280
Height: 720
Depth: 32
Width: 1280
Height: 768
Depth: 16
Width: 1280
Height: 768
Depth: 32
Thanks you.
Easy way to sort a structured list by multiple parameters?
Re: Easy way to sort a structured list by multiple parameter
You would use SortStructuredList() and sort the fields in the opposite order of their priority. In other words you would sort on the tertiary field first, then repeat the sort but do it with the secondary field and finally finish up by sorting on the primary field.
Something like:
It is possible to do it this way because the sorting method used for lists by the PureBasic commands preserves the sort order if a comparison between elements is equal (a stable sort). Note, this same technique will not work with sorting arrays with PureBasic commands because the method used in that case does not preserve the order of a previous sort (unstable).
Something like:
Code: Select all
;this structure and the list are there to just flesh out the example, tailor it using your structure and list
Structure myStruc
Height.i
Width.i
Depth.i
;and possibly other fields
EndStructure
NewList myList.myStruc()
;add elements
;produce a sort by Width, then by Height, then by Depth
SortStructuredList(myList.myStruc(), #PB_Sort_Ascending, OffsetOf(myStruc\Depth), #PB_Integer) ;tertiary field
SortStructuredList(myList.myStruc(), #PB_Sort_Ascending, OffsetOf(myStruc\Height), #PB_Integer) ;secondary field
SortStructuredList(myList.myStruc(), #PB_Sort_Ascending, OffsetOf(myStruc\Width), #PB_Integer) ;primary field
Re: Easy way to sort a structured list by multiple parameter
Demivec,
Thank you! That's a big help.
Thank you! That's a big help.