Chapter Sixteen
Putting It All Together
This is our last time together in this series, so by now (hopefully) this program should have been just a little bit easier. If you were smart, you might have even taken some bits and pieces of previous programs and glued them in! Enough chat, let's develop our multiple-sort program.
First, we will seed the random number generator and clear the screen:
RANDOMIZE TIMER / 3 CLS
Now we will ask for the number of digits to generate, and check that the response was within 5 and 20:
getcount: PRINT "Enter Number of Random Digits to Generate, between 5 and 20 "; INPUT NUMS IF NUMS < 5 OR NUMS > 20 THEN GOTO getcount
Next, we will allocate the storage space needed for both the numeric and string versions of the random numbers:
DIM NUMBER(NUMS), NUMBER$(NUMS)
Let's clear up the screen and print out our first column heading:
CLS LOCATE 1, 2 PRINT "Unsorted List"
Now we will generate our array of random numbers, and print them out as we generate them. We can do this all within the same loop. We will then beep the speaker when we are done, just like we were asked:
FOR N = 1 TO NUMS
NUMBER(N) = INT(50 * RND) + 1
LOCATE N + 2, 2
PRINT NUMBER(N)
NEXT N
BEEPFirst, we will sort the numeric array (as numbers):
FOR OUTER = 1 TO NUMS - 1
FOR INNER = OUTER TO NUMS
IF NUMBER(INNER) < NUMBER(OUTER) THEN SWAP NUMBER(INNER), NUMBER(OUTER)
NEXT INNER
NEXT OUTERNext. we will print out our second column heading and the sorted list, then beep again:
LOCATE 1, 26
PRINT "Sorted As Numbers"
FOR N = 1 TO NUMS
LOCATE N + 2, 26
PRINT NUMBER(N)
NEXT N
BEEPNow to sort them as strings, we first need to convert them to strings:
FOR N = 1 TO NUMS
NUMBER$(N) = STR$(NUMBER(N))
NEXT NNow we sort the string array, the same as the numeric array:
FOR OUTER = 1 TO NUMS - 1
FOR INNER = OUTER TO NUMS
IF NUMBER$(INNER) < NUMBER$(OUTER) THEN SWAP NUMBER$(INNER), NUMBER$(OUTER)
NEXT INNER
NEXT OUTERAnd, just like the others, we will display the column title, and the sorted string array, then beep:
LOCATE 1, 52
PRINT "Sorted as Characters"
FOR N = 1 TO NUMS
LOCATE N + 2, 52
PRINT NUMBER$(N)
NEXT N
BEEPWe're done:
END
For those of you who don't like all of that typing, you can download the final program.
Happy Programming!