190 Rem Bubble Sort

200 FOR P=1 T014.REM MAKE 14 PASSES

210 PRINT CHR$(19):REM FOR DISPLAY

220 FOR C=1 T014:REM 14 COMPARISONS

230 HOLD=NUM(C)

NUM(C)=NUM(C+1):NUM(C+1) = HOLD 250 NEXT C 260 REM........

Because there are 15 items on the list, the maximum number of passes required to sort the list is 14. Line 200 sets up a loop, using the counter P, to make 14 sorting passes through the list.

Line 210 homes the cursor so the next list to be displayed will be just to the right of the preceding list.

Because there are 15 items on the list, each pass requires 14 comparisons and possible interchanges. Line 220 sets up a C loop to make 14 comparisons during each pass of the P loop.

Line 230 is the hold variable. When the value of C is 1, it holds NUM(l).

Line 240 does the comparisons and interchanges. It compares NUM(C+1) to NUM(C). When C is 1, it compares NUM(2) to NUM(l). If NUM(2) is smaller than NUM(l), then NUM(l) is set equal to NUM(2). That puts the smaller number on top. Then NUM(2) is set equal to HOLD. This puts the original value of NUM(l) into NUM(2). The interchange is complete.

If NUM(2) is not smaller than NUM(l), line 240 does not execute, and the two values are not interchanged.

On the next pass through the C loop, C is 2. HOLD holds NUM(2) while NUM(3) is compared to NUM(2). As the loop runs, each pair of items on the list is compared and interchanged if necessary. Line 250 is the bottom of the C loop.

Number of Comparisons—The C loop runs only to 14 even though there are 15 items to be sorted. That's because one of the items being compared is NUM(C+1). When C is 14, NUM(C+1) is 15. That gets the bottom item on the list.

If C ran to 15, the program would sort NUM(16) into this list. What is the value of NUM(16) ? The NUM() array is now in memory. To find out, enter

PRINTNUM(16)

When an array is dimensioned to 15, calling for NUM(16) produces an error. If the array were dimensioned to a larger value, such as 20, but NUM(16) had never been filled since the program was run, its value would be zero.

Reaching down too far while sorting an array causes a problem either way. It may produce a program error. If not, it probably gets a zero. If it gets a zero, it will sort it all the way up to the top of the list. If you find zeros at the top of a list, and they weren't in the unsorted list, your program is reaching too far down the list in the sorting routine.

0 0

Post a comment

  • Receive news updates via email from this site