User Tools

Site Tools


Sorting Arrays of Structures

by Michael Hutton, October 2008

The SORTSALIB library provides a fast way of sorting Arrays of Structures. It will sort the following types of structure elements: bytes(&), integers(%), floating point numbers (both FLOAT 40 and FLOAT 64 (#)), and strings ($).

It can be found at:

Install the library with:


it contains the single function FN_sortSAinit(dir%,smode%)
as with SORTLIB before any sorting can be done it must be initialised:

  sortsa% = FN_sortSAinit(dir%,smode%)

where dir% determines the sorting direction (0 = ascending, 1 = descending) and smode% determines how strings are sorted (0 = normal, 1 = ignore case). You could, if you wanted, initialise it four times with the different options. eg.

  sortascendingnormal% = FN_sortSAinit(0,0)
  sortdescendingnormal% = FN_sortSAinit(1,0)
  sortascendingignore% = FN_sortSAinit(0,1)
  sortdescendingignore% = FN_sortSAinit(1,1)

and then CALL the appropriate variable when needed.

Beware that the calling procedure is slightly different from SORTLIB in that C% = howmany to sort and D% = starting index of element to sort. For example, if we DIM a structure with the following code:

  DIM structure{(100) a&, b%, c, d#, e$}

To sort the entire array of structures using the a& element as the sort key.

  C% = DIM(structure{()},1) : D% = 0 : CALL sortsa%, structure{()}, structure{(0)}.a&

Note that we MUST pass structure{()} as the first parameter and the keys follow that.

To sort part of the array of structures:

  C% = howmany : D% = first : CALL sortsa%, structure{()}, structure{(0)}.a&

To use other variables as keys add them as parameters:

  C% = howmany : D% = first : CALL sortsa%, structure{()}, structure{(0)}.a&, \
  \ structure{(0)}.b%, structure{(0)}.c, structure{(0)}.d#, structure{(0)}.e$

would sort “howmany” elements from the “first' indexed using the byte, integer, float 40, float 64, string as keys in that order.

Note that the key indexes MUST be 0. If any other number is passed the sort will not work, or even crash BB4W.

This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information
sorting_20arrays_20of_20structures.txt · Last modified: 2018/04/17 18:52 by tbest3112