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: http://tech.groups.yahoo.com/group/bb4w/files/Libraries/SORTSALIB.BBC

Install the library with: code format="bb4w" INSTALL @lib$ + "SORTSALIB" code it contains the single function FN_sortSAinit(dir%,smode%) as with SORTLIB before any sorting can be done it must be initialised: code format="bb4w" sortsa% = FN_sortSAinit(dir%,smode%) code 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. code format="bb4w" sortascendingnormal% = FN_sortSAinit(0,0) sortdescendingnormal% = FN_sortSAinit(1,0) sortascendingignore% = FN_sortSAinit(0,1) sortdescendingignore% = FN_sortSAinit(1,1) code 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: code format="bb4w" DIM structure{(100) a&, b%, c, d#, e$} code To sort the entire array of structures using the a& element as the sort key. code format="bb4w" C% = DIM(structure{},1) : D% = 0 : CALL sortsa%, structure{}, structure{(0)}.a& code Note that we MUST pass structure{} as the first parameter and the keys follow that.

To sort part of the array of structures: code format="bb4w" C% = howmany : D% = first : CALL sortsa%, structure{}, structure{(0)}.a& code To use other variables as keys add them as parameters: code format="bb4w" C% = howmany : D% = first : CALL sortsa%, structure{}, structure{(0)}.a&, \ \ structure{(0)}.b%, structure{(0)}.c, structure{(0)}.d#, structure{(0)}.e$ code 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.