<< Sortlist: Sort an arbitrary list of simple elements (e.g., numbers, strings, etc). We use the heapsort algorithm taken from page 75 of Algorithms + Data Structures = Programs by Niklaus Wirth. >> << In order to make sorts faster by not constant creating and destroying temporary lists, we use a global variable that is shared by sift() and sortlist(). >> globlist = {}; << Sift elements left to right into order (ascending or descending depending on the value of ascending). Sift is part of heapsort and should not ever be called by anyone but sortlist(). >> sub sift(left, right, ascending) i = integer(left); j = integer(2 * left); x = globlist[i]; finished = false; repeat while j <= right and not finished if j < right then if ascending then if globlist[j] < globlist[j + 1] then j = j + 1; endif else if globlist[j] > globlist[j + 1] then j = j + 1; endif endif endif if ascending then if x >= globlist[j] then finished = true; endif else if x <= globlist[j] then finished = true; endif endif if not finished globlist[i] = globlist[j]; i = j; j = 2 * i; endif endrepeat globlist[i] = x; endsub << Sort a list of elements (ascending or descending). The ascending parameter is optional and if missing, ascending is assumed. This subroutine implements Wirth's heapsort using a QSL list. We use globlist to avoid recreating the list after every call to sift(). This is necessary because parameters cannot be passed by reference in QSL. >> sub sortlist(list, ascending) if typeof(ascending) = qedit.typeundefined then ascending = true; endif globlist = list; -- We use a global variable to reduce copying, since -- parameters are always copies and not references n = length(globlist); left = integer(integer(n / 2) + 1); right = integer(n); repeat while left > 1 left = left - 1; sift(left, right, ascending); endrepeat repeat while right > 0 x = globlist[1]; globlist[1] = globlist[right]; globlist[right] = x; right = right - 1; sift(left, right, ascending); endrepeat return globlist endsub