' STRSORT.BAS
' This program prompts the user for a list of names and then sorts them
'   alphabetically.

' set maximum number of lines that can be entered and declare string
'   array to hold lines

CONST MAXLINES% = 15
DIM inputLines$(MAXLINES%)

' declare GetText and ShellSort subprograms

DECLARE SUB GetText (strArray$(), numOfElements%)
DECLARE SUB ShellSort (strArray$(), numOfElements%)

CLS

' call GetText subprogram to get input from user; at return the
'   numOfElements% variable will contain number of lines received

GetText inputLines$(), numOfElements%

' call ShellSort subprogram to put inputLines$() array in
'   alphabetical order

ShellSort inputLines$(), numOfElements%

PRINT
PRINT "Sorting results:"
PRINT

FOR i% = 1 TO numOfElements%    ' print contents of sorted array
    PRINT inputLines$(i%)
NEXT i%

END

SUB GetText (strArray$(), count%)

' The GetText subprogram fills the strArray$() array with text
'   entered at the keyboard.  The number of lines that can be
'   entered is determined by the global constant MAXLINES%.
'   Both strArray$() and count% (the number of lines actually
'   entered) are returned to the main program.

PRINT "Enter up to"; MAXLINES%; "lines of text; to end, ";
PRINT "press Enter on a new line."
PRINT
count% = 0
   
DO
    LINE INPUT "-> "; inLine$  ' get line from user
    IF (inLine$ <> "") THEN    ' if line is not blank, copy it
        count% = count% + 1    '   to the strArray$() array
        strArray$(count%) = inLine$
    END IF
' loop until count% = MAXLINES% or an empty line is received
LOOP WHILE (count% < MAXLINES%) AND (inLine$ <> "")

END SUB

SUB ShellSort (strArray$(), numOfElements%)

' The ShellSort subprogram sorts the elements of strArray$() and
'   returns strArray$() to the main program.  The numOfElements%
'   argument contains the number of elements in strArray$().
'   ShellSort sorts elements in decending order.

span% = numOfElements% \ 2
   
DO WHILE span% > 0
    FOR i% = span% TO numOfElements% - 1
        j% = i% - span% + 1
        FOR j% = (i% - span% + 1) TO 1 STEP -span%
            IF strArray$(j%) <= strArray$(j% + span%) THEN EXIT FOR
            ' swap array elements that are out of order
            SWAP strArray$(j%), strArray$(j% + span%)
        NEXT j%
    NEXT i%

    span% = span% \ 2
LOOP

END SUB

