! MExample Program 11-2
! Sort a text file containing names.
! there are ten names in test.dat, sort to test5.dat with a new algorithm
!
! The bubble sort algorithm in Example Program 11.2 scans
! through the entire list, each time comparing every contiguous
! pair of elements in the list. Note that the first scan positions
! the largest element at the right end of the list. This means that
! the second scan needs to cover only the first n-2 pairs of elements,
! not n-1 pairs.
!
! Rewrite example program 11.2 to take advantage of this fact.
! Your for statement might be
! for i=1 to scanlimit
! where scanlimit starts at n-1 and is decreased by one after each scan.
DIM List$ (1)
PRINT "Maximum number of names that you plan to sort (10 in test.dat)";
INPUT Capacity
MAT redim List$(1 to Capacity)
LET ArrayFull$ = "false"
LET Count = 0
CALL OpenFile ("Input file name", "old", #1)
CALL OpenFile ("Output file name", "newold", #2)
DO while more #1 and ArrayFull$ = "false"
LET Count = Count + 1
IF Count <= Capacity then
LINE INPUT #1: List$(Count)
ELSE ! Count > Capacity
LET ArrayFull$ = "true"
! The next statement avoids array overflow
! during sorting in the Sort subroutine.
LET Count = Capacity
END IF
LOOP
IF ArrayFull$ = "true" then
PRINT "Only part of the file could";
PRINT " be read because the"
PRINT "maximum number of names";
PRINT " specified was too small."
END IF
CALL Sort (List$, Count)
ERASE #2
FOR Index = 1 to Count
PRINT #2: List$(Index)
NEXT Index
CLOSE #1
CLOSE #2
PRINT "A list of"; Count; "names has been sorted."
END ! of main program
SUB OpenFile (Prompt$, Mode$, #9)
! Prompt for file name and open file.
LET FileOpened$ = "false"
DO
WHEN error in
PRINT Prompt$;
LINE INPUT FileName$
OPEN #9: name FileName$, create Mode$
LET FileOpened$ = "true"
USE
PRINT "Error: "; extext$
PRINT "Check path name and try again."
END WHEN
LOOP until FileOpened$ = "true"
END SUB ! OpenFile
SUB Sort (Array$(), N)
! Bubble sort a string array
! in ascending alphabetic order.
DO
LET Sorted$ = "true"
LET scanlimit=n-1
FOR Index = 1 to scanlimit
IF Array$(Index) > Array$(Index + 1) then
LET Temp$ = Array$(Index)
LET Array$(Index) = Array$(Index + 1)
LET Array$(Index + 1) = Temp$
LET Sorted$ = "false"
END IF
LET scanlimit=scanlimit-1
NEXT Index
LOOP until Sorted$ = "true"
END SUB ! Sort