One Step Further: Processing Large Arrays by Using Methods in the Array Class


One Step Further: Processing Large Arrays by Using Methods in the Array Class

In previous sections, you learned about using arrays to store information during program execution. In this section, you'll learn about using methods in the Array class of the Microsoft .NET Framework, which you can use to quickly sort, search, and reverse the elements in an array, as well as perform other functions. The sample program I've created demonstrates how these features work especially well with very large arrays. You'll also learn how to use the ProgressBar control.

The Array Class

When you create arrays in Visual Basic, you are using a base class that is defined by Visual Basic for implementing arrays within user-created programs. This Array class also provides a collection of methods that you can use to manipulate arrays while they are active in programs. The most useful methods include Array.Sort, Array.Find, Array.Reverse, Array.Copy, and Array.Clear. You can locate other interesting methods by experimenting with the Array class in the Code Editor (by using Microsoft IntelliSense) and by checking the online help. The Array class methods function much like the .NET Framework methods you have already used in this book; that is, they are called by name and (in this case) require a valid array name as an argument. For example, to sort an array of temperatures (such as the Temperatures array that you created in the last exercise), you would use the following syntax:

Array.Sort(Temperatures)

You would make such a call after the Temperatures array had been declared and filled with data in the program. When Visual Basic executes the Array.Sort method, it creates a temporary storage location for the array in memory and uses a sorting routine to reorganize the array in alphanumeric order. After the sort is complete, the original array is shuffled in ascending order, with the smallest value in array location 0 and the largest value in the last array location. With the Temperatures example above, the sort would produce an array of daily temperatures organized from coolest to hottest.

In the following exercise, you'll see how the Array.Sort and Array.Reverse methods can be used to quickly reorder a large array containing six-digit numbers randomly selected between 0 and 1,000,000. You'll also learn how to use the ProgressBar control, an interesting user interface tool that provides useful visual feedback for the user during long sorts. (The ProgressBar control is located on the Common Controls tab of the Toolbox, and we're using it now for the first time.)

Use Array methods to sort an array of 3000 elements

  1. On the File menu, click Open Project, and then open the Array Class Sorts project located in the c:\vb05sbs\chap11 folder.

  2. Display the form if it is not already visible.

    Your screen looks like this:

    graphic

    This form looks similar to the earlier projects in this chapter and features a test box for displaying array data. However, it also contains three buttons for manipulating large arrays and a progress bar object that gives the user feedback during longer array operations. (Visual feedback is useful when computations take longer than a few seconds to complete, and if you use this code to sort an array of 3000 array elements, a slight delay is inevitable.)

  3. Click the progress bar on the form.

    The ProgressBar1 object is selected on the form and is listed in the Properties window. I created the progress bar object by using the ProgressBar control on the Common Controls tab in the Toolbox. A progress bar is designed to display the progress of a computation by displaying an appropriate number of colored rectangles arranged in a horizontal progress bar. When the computation is complete, the bar is filled with rectangles. You've probably seen this bar many times while you downloaded files or installed programs within Microsoft Windows. Now you can create one in your own programs!

    The important properties that make a progress bar work are the Minimum, Maximum, and Value properties, and these are typically manipulated using program code. (The other progress bar properties, which you can examine in the Properties window, control how the progress bar looks and functions.) You can examine how the Minimum and Maximum properties are set by looking at this program's Form1_Load event procedure.

  4. Double-click the form to display the Form1_Load event procedure.

    You see the following code:

    graphic

    For a progress bar to display an accurate indication of how long a computing task will take to complete, you need to set relative measurements for the beginning and the end of the bar. This is accomplished with the Minimum and Maximum properties, which are set to match the first and the last elements in the array that we are building. As I have noted, the first array element is always 0 but the last array element depends on the size of the array, so I have used the UBound function to return that number and set the progress bar Maximum property accordingly. The array that we are manipulating in this exercise is RandArray, a Long integer array declared initially to hold 500 elements (0 to 499).

  5. Click the Start Debugging button to run the program.

    The program runs, and the Array Class Sorts form appears on the screen. In its Form1_Load event procedure, the program declared an array named RandArray and dimensioned it with 500 elements. A progress bar object was calibrated to track a calculation of 500 units (the array size), and the number 500 appears to the right of the progress bar (the work of a label object and the UBound function).

  6. Click the Fill Array button.

    The program loads RandArray with 500 random numbers (derived by the Rnd function), and displays the numbers in the text box. As the program processes the array and fills the text box object with data, the progress bar is slowly filled with green rectangles. Your screen looks like this when the process is finished:

    graphic

    The code that produced this result is the Button1_Click event procedure, which contains the following program statements:

    'Fill the array with random numbers and display in text box Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click     Dim i As Integer     For i = 0 To UBound(RandArray)         RandArray(i) = Int(Rnd() * 1000000)         TextBox1.Text = TextBox1.Text & RandArray(i) & vbCrLf         ProgressBar1.Value = i  'move progress bar     Next i End Sub

    To get random numbers that are integers, I used the Int and Rnd functions together as I did in Chapter 2, “Writing Your First Program,” and I multiplied the random number produced by Rnd by 1,000,000 to get whole numbers that are six digits or less. Assigning these numbers to the array is facilitated by using a For…Next loop with an array index that matches the loop counter (i). Filling the array is an extremely fast operation; the slow-down (and the need for the progress bar) is caused by the assignment of array elements to the text box object one at a time. This involves updating a user interface component on the form 500 times, and the process takes a few seconds to complete. It is instructional, however—the delay provides a way for me to show off the ProgressBar control. Since the progress bar object has been calibrated to use the number of array elements as its maximum, assigning the loop counter (i) to the progress bar's Value property allows the bar to display exactly how much of the calculation has been completed.

  7. Click the Sort Array button.

    The program follows a similar process to sort RandArray, this time using the Array.Sort method to reorder the array in ascending order. (The 500 elements are listed from lowest to highest.) Your screen looks like this:

    graphic

    The code that produced this result is the Button2_Click event procedure, which contains the following program statements:

    'Sort the array using the Array.Sort method and display Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click     Dim i As Integer     TextBox1.Text = ""     Array.Sort(RandArray)     For i = 0 To UBound(RandArray)         TextBox1.Text = TextBox1.Text & RandArray(i) & vbCrLf         ProgressBar1.Value = i  'move progress bar     Next i End Sub

    This event procedure clears the text box object when the user clicks the Sort Array button, and then sorts the array by using the Array.Sort method described earlier. The sorting process is very quick. Again, the only slow down is rebuilding the text box object one line at a time in the For…Next loop, a process that is reported by the ProgressBar1 object and its Value property. See how simple it is to use the Array.Sort method?

  8. Click the Reverse button.

    The program uses the Array.Reverse method to manipulate RandArray, reordering the array in backward or reverse order; that is, the first element becomes last and the last element becomes first.

    NOTE
    This method does not always produce a sorted list; the array elements are in descending order only because RandArray had been sorted previously in ascending order by the Array.Sort method. (To examine the list more closely, use the scroll bars or the arrow keys.)

    Your screen looks like this:

    graphic

    The code that produced this result is the Button3_Click event procedure, which contains the following program statements:

    'Reverse the order of array elements using Array.Reverse Private Sub Button3_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button3.Click     Dim i As Integer     TextBox1.Text = ""     Array.Reverse(RandArray)     For i = 0 To UBound(RandArray)         TextBox1.Text = TextBox1.Text & RandArray(i) & vbCrLf         ProgressBar1.Value = i  'move progress bar     Next i End Sub

    This event procedure is identical to the Button2_Click event procedure, with the following exception:

      Array.Sort(RandArray)

    has become

      Array.Reverse(RandArray)

  9. Click the Stop Debugging button to end the program.

  10. Scroll to the top of the Code Editor, and locate the program statement that declares the RandArray array:

    Dim RandArray(0 To 499) As Long

  11. Replace 499 in the array declaration statement with 2999.

    The statement now looks like this:

    Dim RandArray(0 To 2999) As Long

  12. Run the program again to see how declaring and filling an array with 3000 elements affects program performance.

    Because processing 3000 elements is much more work, Visual Basic takes a little while to update the text box object again and again as you fill, sort, and reverse RandArray. However, the progress bar keeps you posted, and you can see that with just a small change, you can adapt what you've learned in this chapter to different situations. (The secret was using the UBound function to report the size of the array to the program's event procedures, rather than “hard coding” the upper bound at 499.)

You can further experiment with this program by adding a Randomize statement to the Form1_Load event procedure (to make the results truly random each time that you run the program), or by trying additional array sizes and array types. (Try an array size of 100, 800, 2000, or 5000 elements, for example.) If you try larger numbers, you'll eventually exceed the amount of data that the text box object can display, but it takes you a while before you exceed the maximum array size allowed by Visual Basic.

If you want to focus on array operations without displaying the results, place a comment character (') before each line of code that manipulates a text box object to “comment out” the text box (but not the progress bar) portions of the program. You'll be amazed at how fast array operations run when the results do not need to be displayed on the form. (An array of 100,000 elements loads in just a few seconds.)



Microsoft Visual Basic 2005 Step by Step
Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
ISBN: B003E7EV06
EAN: N/A
Year: 2003
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net