Easy way to sort a structured list by multiple parameters?

Just starting out? Need help? Post your questions and find answers here.
CharlesT
User
User
Posts: 19
Joined: Sun Jan 07, 2018 10:09 pm

Easy way to sort a structured list by multiple parameters?

Post by CharlesT »

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.
User avatar
Demivec
Addict
Addict
Posts: 4091
Joined: Mon Jul 25, 2005 3:51 pm
Location: Utah, USA

Re: Easy way to sort a structured list by multiple parameter

Post by Demivec »

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:

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
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).
CharlesT
User
User
Posts: 19
Joined: Sun Jan 07, 2018 10:09 pm

Re: Easy way to sort a structured list by multiple parameter

Post by CharlesT »

Demivec,

Thank you! That's a big help. :D
Post Reply