sort_list(list) takes a tab-separated list of values as a string and returns it in the same format but ordered based on the return value of do_single_sort(left, right).
Uses no objects or anything like that, just simple string manipulation. This is some pretty old code so I apologize for how unreadable it is.
$alpha = "abcdefghijklmnopqrstuvwxyz_";
function sort_list( %m )
{
%count = getFieldCount( %m );
if ( !strLen( %m ) || %count <= 1 )
{
return %m;
}
%middle = mFloor( %count / 2 );
for ( %i = 0 ; %i < %middle ; %i++ )
{
%left = %left @ ( strLen( %left ) ? "\t" : "" ) @ getField( %m, %i );
}
for ( %i = %middle ; %i < %count ; %i++ )
{
%right = %right @ ( strLen( %right ) ? "\t" : "" ) @ getField( %m, %i );
}
%left = merge_sort( %left );
%right = merge_sort( %right );
return merge( %left, %right );
}
function do_single_sort( %left, %right )
{
// I'm pretty sure you can just use strStr instead of this mess.
%lln = strLen( %left );
%rln = strLen( %right );
if ( %lln < %rln )
{
%ln = %lln;
%rt = 1;
}
else
{
%ln = %rln;
%rt = 0;
}
for ( %i = 0 ; %i < %ln ; %i++ )
{
%lfs = getSubStr( %left, %i, 1 );
%rfs = getSubStr( %right, %i, 1 );
%lps = strPos( $alpha, %lfs );
%rps = strPos( $alpha, %rfs );
if ( %lps > %rps )
{
return 1;
}
if ( %rps > %lps )
{
return 0;
}
}
return %rt;
}
function merge( %left, %right )
{
%left = strReplace( %left, " ", "\x01" );
%left = strReplace( %left, "\t", " " );
%right = strReplace( %right, " ", "\x01" );
%right = strReplace( %right, "\t", " " );
while( getWordCount( %left ) > 0 || getWordCount( %right ) > 0 )
{
if ( getWordCount( %left ) > 0 && getWordCount( %right ) > 0 )
{
if ( !do_single_sort( firstWord( %left ), firstWord( %right ) ) )
{
%result = %result @ ( strLen( %result ) ? "\t" : "" ) @ firstWord( %left );
%left = restWords( %left );
}
else
{
%result = %result @ ( strLen( %result ) ? "\t" : "" ) @ firstWord( %right );
%right = restWords( %right );
}
}
else if ( getWordCount( %left ) > 0 )
{
%result = %result @ ( strLen( %result ) ? "\t" : "" ) @ firstWord( %left );
%left = restWords( %left );
}
else if ( getWordCount( %right ) > 0 )
{
%result = %result @ ( strLen( %result ) ? "\t" : "" ) @ firstWord( %right );
%right = restWords( %right );
}
}
%left = strReplace( %left, " ", "\t" );
%left = strReplace( %left, "\x01", " " );
%right = strReplace( %right, " ", "\t" );
%right = strReplace( %right, "\x01", " " );
return %result;
}
Specifically, this implements the merge sort algorithm and is O(log n).