Arrays and Sorting

by Welopez

Computers are marvelous inventions, but how do you make them do what you want? Simple, you must learn what the computer is capable of and how to give instructions to the computer. When you've done all that, if your program does not perform, 99 times out of a hundred you've made an error. Computers do not make errors! They simply respond to the code you have entered.

Writing code to perform a task is simple. Debugging the code for a program which bombs is where programmers spend most of their time. Get used to it! Learn the logic required to perform a comparison. Learn how computers evaluate conditions. Learn to use the debugger to see what your code is doing during each step of execution, allowing you to modify or correct your code.

You will use arrays for a LISTBOX or COMBOBOX, as well as many other tasks when programming. Let's begin with this fairly simple code. Enter only the first line of five DATA elements to begin with; we'll edit the code to add more DATA elements later. Multiple DATA elements on the same line are separated using a comma. If string and numerical DATA is mixed on the same line, use quotation marks (") to enclose each data element, not the entire line!

      'Sorting Strings
      'by Welopez

      FOR k=1 TO 5
      READ anItem$
      PRINT anItem$
      NEXT k
      PRINT
      PRINT "There are "; k; " items in the data list."
      PRINT
      INPUT "Press ENTER to continue."; resp$
      'Clear the screen, restore the data, load an array for sorting
      CLS
      RESTORE
      FOR k=1 TO 5
          READ dummy$
          content$(k)=dummy$
      NEXT k

      PRINT "These strings have been loaded into content$() array."
      PRINT
      FOR k=1 TO 5
          PRINT "content$("; k ;")", content$(k)  'shows the array has been loaded
      NEXT k
      PRINT
      INPUT "Press ENTER to sort the array."; resp$
      'Clear the screen, sort the array, print the array
      CLS
      '=== A simple bubble-sort to order the array list
      elements=k-1  'Remember, k=6, we want elements to equal k-1
      FOR i=1 TO elements        'Compare the complete array list
          FOR j=1 TO elements-1  'The j loop must be one fewer than total elements
              IF content$(j)>content$(j+1) THEN
                  temp$=content$(j)
                  content$(j)=content$(j+1)
                  content$(j+1)=temp$
              END IF
          NEXT j
      NEXT i
      '=== End of the bubble-sort

      PRINT "The sorted array looks like this:"
      PRINT
      FOR k=1 TO 5
          PRINT "content$("; k; ")", content$(k)
      NEXT k
      PRINT
      PRINT "Now you should be able to modify the list of items"
      PRINT "contained in the data statements."
      PRINT
      PRINT "Before continuing, remove the apostrophe (') to"
      PRINT "make the final 3 lines of data statements available."
      PRINT
      PRINT "You will receive a 'Read past end of data' error"
      PRINT "until you make the change."
      PRINT
      INPUT "Press ENTER to continue."; resp$
      CLS

      PRINT "The modified data list looks like this."
      PRINT
      RESTORE
      DIM content$(15)
      WHILE 1
          READ dummy$
          IF dummy$="zzyzx" THEN EXIT WHILE  'out of here if done
          counter=counter+1  'count the number of elements
          PRINT dummy$         'show the element just read
          content$(counter)=dummy$  'put the dummy$ into content$() array
      WEND
      PRINT
      PRINT "There are "; counter; " data items in the list."
      PRINT

      INPUT "Press ENTER to sort the array."; resp$
      'Clear the screen, sort the array, print the array
      CLS

      FOR i=1 TO counter
          FOR j=1 TO counter-1
              IF content$(j)>content$(j+1) THEN
                  temp$=content$(j)
                  content$(j)=content$(j+1)
                  content$(j+1)=temp$
              END IF
          NEXT j
      NEXT i
      CLS
      PRINT "The sorted array looks like this:"
      PRINT
      FOR k=1 TO counter
          PRINT "content$("; k; ")", content$(k)
      NEXT k
      PRINT
      PRINT "Program has ended."

      END

      DATA rose, orchid, daisy, poppy, geranium
      'DATA "bowling ball", "10 penny nail", "proton", "microscope", "guitar"
      'DATA "#22 fastener", "280-Z spare tire", "747 Jumbo Jet"
      'DATA "00 buckshot pellet", "76 trombones", "zzyzx"

DATA statements can be entered anywhere in your program, but most programmers put them all at the beginning or end of the code. When you issue a READ statement, JB begins with the first DATA value. The next READ statement gets the second DATA value, and so on, until you reach the end of the list.

The FOR/NEXT loop at the top of this code READs the first five DATA values. But then it says there are six data items! Definitely WRONG!

A FOR/NEXT loop executes until the value is greater than the assigned parameter, FOR k=1 TO 5, and then execution falls through. In this case, when k=6 the loop ends, and now you know why it claims it has read six items! Not understanding the FOR/NEXT loop will often result in an OS error if there are no additional DATA items.

Continuing to the next page (and block of code), we must issue a RESTORE statement if we intend to begin at the beginning of the DATA items which have already been read. When loading an array directly from DATA statements in a program, they must first be read to a dummy value, then the array element can be set to equal the dummy value. If you are reading strings, the array must contain the "$" identifier; numerical values do not require the "$".

Now we can print the contents of the array. Hey, we did it!

Fine, now lets sort it. We do not have to RESTORE an array. Sorting an array requires looping through each element and comparing it to the next element. If this element is larger than (>) the next element (ascending order), hold it in a temporary value so it will not be over-written, set this element equal to the next element, and finally set the next element equal to the temporary value. If you need to sort the array in descending order, use the less than symbol (<). The next screen shows the sorted array elements.

Now let's add the rest of the data elements. We include the RESTORE statement to begin at the beginning, and the DIM content$(15) statement because we're going to work with more than 11 DATA elements in this array. We load content$() array with a WHILE/WEND loop, exiting the loop if we READ "zzyzx" which is a sentinel to mark the end of the DATA statements. We EXIT WHILE before incrementing the counter by adding 1.

Now that we know how many DATA values have been loaded into content$(), we can perform a new sort, using exactly the same code as before.

Wait just a cotten picking minute! I may not be the sharpest knife in the drawer... but I know that #22 fastener should be listed after the 00 buckshot and 10 penny nail! What did my computer do wrong?

Nothing. While 22 is certainly greater than 00 or 10, the string begins with #, which is ASCII(35), and is smaller than zero, ASCII(48) and one, ASCII(49). String$ are sorted according to ASCII values. For the same reason, 76 trombones is greater than 280-Z spare tire and 747 Jumbo Jet. String values are compared from left to right, until an inequality allows the > or < comparison to evaluate as true.

The sort routine in this program is a simple bubble-sort and will be fast enough for an array of a few hundred items. If you have several thousand items and need more speed, see: FUNCTION jbSORT, an adaptation of the Quick Sort for JB and multi-dimension arrays.

Okay, I understand that now... but my array has several dimensions for name, address, phone, etc. How am I supposed to sort that? Think the problem through and you'll most likely come up with the answer. If not, you can try: SORTING for Beginners. Same bubble-sort, just a few extra lines to keep the phone numbers aligned with the names and addresses.

It is generally easier to save DATA to a file on the computer hard drive, where the data can be loaded with INPUT statements if you do not want to lose changes between program runs. FILE OPERATIONs are another topic which you should study. Look in the help files as well as the Articles and Tutorials.

The most powerful computer you have access to lies between your ears. Always try to reason through a problem, outlining the tasks you have to accomplish, BEFORE you begin to write your program. If your program still bombs, try single-stepping through the code, one line at a time, using the debugger. Pay very close attention to the values of variables at every point in the code. If you are still clueless, post a question in the forum and include enough code for others to search for an error