! 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

!

 

! Rewrite the sorting algorithm of Example Program 11.2 so that

! it will sort an array in either ascending or descending order.

! You need to pass a third parameter to the sub-routine,

! as string variable containing the letter "A" for ascending sort

! or the letter "D" for descending sort.

! Test your program by reading the file of names, test.dat,

! created in example program 11.3, and

! writing the sorted list of names to a new file such as test2.dat.

 

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

 

PRINT "Ascending or descending sort? (a,d) ";

INPUT dir$

IF dir$="a" then

CALL Sort (List$, Count)

ELSE

CALL revsort(list$,count)

END IF

 

 

 

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."

PRINT

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"

FOR Index = 1 to n-1

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

NEXT Index

LOOP until Sorted$ = "true"

END SUB ! Sort

SUB revsort (Array$(), N)

! Bubble sort a string array

! in ascending alphabetic order.

DO

LET Sorted$ = "true"

FOR Index = 1 to n-1

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

NEXT Index

LOOP until Sorted$ = "true"

END SUB ! Sort