EasyManua.ls Logo

Sinclair QL - Page 120

Sinclair QL
135 pages
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
red black blue magenta green cyan yellow white
reveals the problem. We compare black with red and decrease p to the value, 1. We come round
again and try to compare black with a variable colour$(p-1) which is colour$(0) which does not exist.
This is a well-known problem in computing and the solution is to "post a sentinel" on the end of the
array. Just before entering the REPeat loop we need:
LET colour$(0) = comp$
Fortunately SuperBASIC allows zero subscripts, otherwise the problem would have to be solved at
the expense of readability.
MODIFIED PROGRAM
100 REM Insertion Sort
110 DIM colour$(8,7)
120 FOR item = 1 TO 8 : READ colour$(item)
130 FOR item = 2 TO 8
140 LET p=item
150 LET comp$ = colour$(p)
160 LET colour$(0) = comp$
170 REPeat compare
180 IF comp$ >= colour$(p-1) : EXIT compare
190 LET colour$(p) = colour$(p-1)
200 LET p = p-1
210 END REPeat compare
220 LET colour$(p) = comp$
230 END FOR item
240 PRINT"Sorted..." ! colour$
250 DATA "black","blue","magenta","red"
260 DATA "green","cyan","yellow","white"
COMMENT
1. The program works well. It has been tested with awkward data:
A A A A A A A
B A B A B A B
A B A B A B A
B C D E F G H
G F E D C B A
2. An insertion sort is not particularly fast, but it can be useful for adding a few items to an already
sorted list. It is sometimes convenient to allow modest amounts of time frequently to keep items in
order rather than a substantial amount of time less frequently to do a complete re-sorting.
You now have enough background knowledge to follow a development of the handling of the file of
seven names and telephone numbers.
SORTING A MICRODRIVE FILE
In order to sort the file 'phone' into alphabetical order of names we must read it into an internal array,
sort it, and then create a new file which will be in alphabetical order of names.
It is never good practice to delete a file before its replacement is clearly established and proven
correct. You should therefore copy the file first, as security using a different name. The required
processes are as follows:
1. Copy the file 'phone' to 'phone_temp'
2. Read the file 'phone' into an array

Other manuals for Sinclair QL

Related product manuals