1 / 58

Exploring Arrays in Visual Basic: Introduction, Declaration, Allocation, and Examples

Understand arrays in Visual Basic, from declaration to allocation and initialization. Learn to use arrays to manipulate data effectively and efficiently. Includes examples for sorting, searching, and multidimensional arrays.

mcintyrem
Download Presentation

Exploring Arrays in Visual Basic: Introduction, Declaration, Allocation, and Examples

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 7 - Arrays Outline7.1 Introduction7.2   Arrays7.3   Declaring and Allocating Arrays7.4   Examples Using Arrays 7.4.1 Allocating an Array7.4.2  Initializing the Values in an Array7.4.3  Summing the Elements of an Array7.4.4  Using Arrays to Analyze Survey Results7.4.5  Using Histograms to Display Array Data Graphically7.5   Passing Arrays to Procedures7.6   Passing Arrays:ByValvs.ByRef7.7   Sorting Arrays7.8   Searching Arrays: Linear Search and Binary Search7.8.1  Searching an Array with Linear Search7.8.2  Searching a Sorted Array with Binary Search7.9   Multidimensional Rectangular and Jagged Arrays7.10   Variable-Length Parameter Lists7.11   ForEach/NextRepetition Structure

  2. 7.1 Introduction • Arrays • Arrays are data structures consisting of data items of the same type • “Static” entities • They remain the same size once they are created

  3. 7.2 Arrays • Array • Group of contiguous memory locations that have the same name and the same type • Position number • Values that indicate specific locations within arrays • The first element in every array is the zeroth element • Length property • Every array in Visual Basic “knows” its own length through the Length property • GetUpperBound method • Returns the index of the last element in the array • The value returned by this GetUpperBound is one less than the value of the array’s Length property

  4. 7.2 Arrays Name of array (note that all elements of this array have the same name, numberArray) numberArray(0) -45 numberArray(1) 6 numberArray(2) 0 numberArray(3) 72 numberArray(4) 1543 numberArray(5) -89 numberArray(6) 0 numberArray(7) 62 numberArray(8) -3 numberArray(9) 1 Position number (index or subscript) of the element within array numberArray numberArray(10) 6453 78 numberArray(11) Fig. 7.1 Array consisting of 12 elements.

  5. 7.3 Declaring and Allocating Arrays • Memory • The amount of memory required by an array depends on the length of the array and the size of the data type of the elements in the array • Keyword New • It is used to specify the size of the array and allocate memory for the array • Array bounds • Determine what indices can be used to access an element in the array • Initializer list • Specify the initial values of the elements in the array • Keyword Nothing • Denotes an empty reference

  6. 7.4 Examples Using Arrays • Several examples that demonstrate • Declaration • Allocation • Initialization of arrays

  7. A variable capable of storing a reference to an array of Integer elements Allocate an array of 10 elements using New and assigns it to array Appends to output the headings for the columns displayed by the program For structure is used to append the index number and value of each array element to output The length property returns the number of elements in the array 1 ' Fig. 7.2: CreateArray.vb 2 ' Declaring and allocating an array. 3 4 Imports System.Windows.Forms 5 6 Module modCreateArray 7 8 Sub Main() 9 Dim output As String 10 Dim i As Integer 11 12Dim arrayAs Integer() ' declare array variable 13 array = New Integer(9) {} ' allocate memory for array 14 15 output &= "Subscript " & vbTab & "Value" & vbCrLf 16 17 ' display values in array 18For i = 0To array.GetUpperBound(0) 19 output &= i & vbTab & array(i) & vbCrLf 20 Next 21 22 output &= vbCrLf & "The array contains " & _ 23 array.Length &" elements." 24 25 MessageBox.Show(output, "Array of Integer Values", _ 26 MessageBoxButtons.OK, MessageBoxIcon.Information) 27 End Sub ' Main 28 29 End Module' modCreateArray CreateArray.vb

  8. 7.4 Examples Using Arrays CreateArray.vb

  9. One statement is used to declare the two arrays Allocates the 10 elements of array1 with New and initialize the values in the array, using an initializer list Allocates array2, whose size is determined by arry1.GetUpperBound(0), so that array1 and array2 have the same upper bound Initializes each element in array2 to the even integers Uses the values in the arrays to build String output, which is displayed in a MessageBox 1 ' Fig. 7.3: InitArray.vb 2 ' Initializing arrays. 3 4 Imports System.Windows.Forms 5 6 Module modInitArray 7 8 Sub Main() 9 Dim output As String 10 Dim i As Integer 11 12Dim array1, array2 As Integer() ' declare two arrays 13 14 ' initializer list specifies number of elements 15 ' and value of each element 16 array1 = NewInteger() {32, 27, 64, 18, 95, _ 17 14, 90, 70, 60, 37} 18 19 ' allocate array2 based on length of array1 20 array2 = NewInteger(array1.GetUpperBound(0)) {} 21 22 ' set values in array2 by a calculation 23For i = 0To array2.GetUpperBound(0) 24 array2(i) = 2 + 2 * i 25 Next 26 27 output &= "Subscript " & vbTab & "Array1" & vbTab & _ 28 "Array2" & vbCrLf 29 30 ' display values for both arrays 31For i = 0To array1.GetUpperBound(0) 32 output &= i & vbTab & array1(i) & vbTab & array2(i) & _ 33 vbCrLf 34 Next 35 InitArray.vb

  10. 36 MessageBox.Show(output, "Array of Integer Values", _ 37 MessageBoxButtons.OK, MessageBoxIcon.Information) 38 End Sub' Main 39 40 End Module' modInitArray InitArray.vb

  11. Declares, allocates and initializes the 10-element array, array Performs the addition 1 ' Fig. 7.4: SumArray.vb 2 ' Computing sum of elements in array. 3 4 Imports System.Windows.Forms 5 6 Module modSumArray 7 8 SubMain() 9Dim array AsInteger() = NewInteger() _ 10 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 11 12 Dim total AsInteger = 0, i AsInteger = 0 13 14 ' sum array element values 15 For i = 0To array.GetUpperBound(0) 16 total += array(i) 17 Next 18 19 MessageBox.Show("Total of array elements: " & total, _ 20 "Sum the elements of an Array", MessageBoxButtons.OK, _ 21 MessageBoxIcon.Information) 22 EndSub ' Main 23 24 EndModule ' modSumArray SumArray.vb

  12. Array responses is a 40-element integer array containing the student’s responses to the survey Reads the responses from the array responses one at a time and increments one of the 10 counters in the frequency array 1 ' Fig. 7.5: StudentPoll.vb 2 ' Using arrays to display poll results. 3 4 Imports System.Windows.Forms 5 6 Module modStudentPoll 7 8 Sub Main() 9 Dim answer, rating AsInteger 10 Dim output AsString 11 12 ' student response array (typically input at run time) 13 Dim responses As Integer() 14 responses = New Integer() {1, 2, 6, 4, 8, 5, 9, 7, _ 15 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, _ 16 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10} 17 18 ' response frequency array (indices 0 through 10) 19 Dim frequency As Integer() = New Integer(10) {} 20 21 ' count frequencies 22For answer = 0To responses.GetUpperBound(0) 23 frequency(responses(answer)) += 1 24 Next 25 26 output &= "Rating " & vbTab & "Frequency " & vbCrLf 27 28 For rating = 1To frequency.GetUpperBound(0) 29 output &= rating & vbTab & frequency(rating) & vbCrLf 30 Next 31 StudentPoll.vb

  13. 32 MessageBox.Show(output, "Student Poll Program", _ 33 MessageBoxButtons.OK, MessageBoxIcon.Information) 34 End Sub ' Main 35 36 End Module' modStudentPoll StudentPoll.vb

  14. Nested For loops append the bars to the String that is displayed in the MessageBox Inner For structure counts from 1 to array(i), which is the value in the ith index of array1 1 ' Fig. 7.6: Histogram.vb 2 ' Using data to create histograms. 3 4 Imports System.Windows.Forms 5 6 Module modHistogram 7 8 Sub Main() 9 Dim output AsString ' output string 10 Dim i, j AsInteger ' counters 11 12 ' create data array 13 Dim array1 AsInteger() = NewInteger() _ 14 {19, 3, 15, 7, 11, 9, 13, 5, 17, 1} 15 16 output &= "Element " & vbTab & "Value " & vbTab & _ 17 "Histogram" 18 19For i = 0To array1.GetUpperBound(0) 20 output &= vbCrLf & i & vbTab & array1(i) & vbTab 21 22For j = 1To array1(i) 23 output &= "*"' add one asterisk 24 Next 25 26 Next 27 28 MessageBox.show(output, "Histogram Printing Program", _ 29 MessageBoxButtons.OK, MessageBoxIcon.Information) 30 End Sub ' Main 31 32 End Module ' modHistogram Histogram.vb

  15. Histogram.vb

  16. 1 ' Fig. 7.7: RollDie.vb 2 ' Rolling 12 dice with frequency chart. 3 4 ' Note: Directory.GetCurrentDirectory returns the directory of 5 ' the folder where the current project is plus 6 ' "bin/". This is where the images must be placed 7 ' for the example to work properly. 8 9 Imports System.IO 10 Imports System.Windows.Forms 11 12 PublicClass FrmRollDie 13 Inherits System.Windows.Forms.Form 14 15 Dim randomNumber As Random = New Random() 16 Dim frequency AsInteger() = NewInteger(6) {} 17 18 ' labels 19 FriendWithEvents lblDie1 As Label 20 FriendWithEvents lblDie2 As Label 21 FriendWithEvents lblDie3 As Label 22 FriendWithEvents lblDie4 As Label 23 FriendWithEvents lblDie5 As Label 24 FriendWithEvents lblDie6 As Label 25 FriendWithEvents lblDie7 As Label 26 FriendWithEvents lblDie8 As Label 27 FriendWithEvents lblDie9 As Label 28 FriendWithEvents lblDie11 As Label 29 FriendWithEvents lblDie10 As Label 30 FriendWithEvents lblDie12 As Label 31 32 ' text box 33 FriendWithEvents txtDisplay As TextBox 34 RollDie.vb

  17. 35 ' button 36 FriendWithEvents cmdRoll As Button 37 38 ' Visual Studio .NET generated code 39 40 ' event handler for cmdRoll button 41 PrivateSub cmdRoll_Click(ByVal sender As System.Object, _ 42 ByVal e As System.EventArgs) Handles cmdRoll.Click 43 44 ' pass labels to a method that 45 ' randomly assigns a face to each die 46 DisplayDie(lblDie1) 47 DisplayDie(lblDie2) 48 DisplayDie(lblDie3) 49 DisplayDie(lblDie4) 50 DisplayDie(lblDie5) 51 DisplayDie(lblDie6) 52 DisplayDie(lblDie7) 53 DisplayDie(lblDie8) 54 DisplayDie(lblDie9) 55 DisplayDie(lblDie10) 56 DisplayDie(lblDie11) 57 DisplayDie(lblDie12) 58 59 Dim total AsDouble = 0 60 Dim i AsInteger 61 62 For i = 1To frequency.GetUpperBound(0) 63 total += frequency(i) 64 Next 65 66 txtDisplay.Text = "Face" & vbTab & vbTab & "Frequency" & _ 67 vbTab & vbTab & "Percent" & vbCrLf 68 RollDie.vb

  18. We loop through array frequency to output the frequency values Calculates random numbers from 1-6 Uses face’s value as the index for array frequency to determine which element should be incremented 69 ' output frequency values 70For i = 1To frequency.GetUpperBound(0) 71 txtDisplay.Text &= i & vbTab & vbTab & frequency(i) & _ 72 vbTab & vbTab & vbTab & String.Format("{0:N}", _ 73 frequency(i) / total * 100) & "%" & vbCrLf 74 Next 75 76 EndSub' cmdRoll_Click 77 78 ' simulate roll, display proper 79 ' image and increment frequency 80 Sub DisplayDie(ByVal lblDie As Label) 81Dim face AsInteger = 1 + randomNumber.Next(6) 82 83 lblDie.Image = _ 84 Image.FromFile(Directory.GetCurrentDirectory & _ 85 "\Images\die" & face & ".png") 86 87 frequency(face) += 1 88 EndSub' DisplayDie 89 90 EndClass' FrmRollDie RollDie.vb

  19. RollDie.vb

  20. 7.5 Passing Arrays to Procedures • Passing the Array • Specify the name of the array without using parentheses • Every array object “knows” its own upper bound • Do not need to pass the upper bound of the array as a separate argument • In Visual Basic, arrays always are passed by reference • Receiving the array • The procedure’s parameter list must specify that an array will be recieved

  21. Appends the five elements of array1 to String output Passes array1 to procedure ModifyArray Appends the elements of array1 to output 1 ' Fig. 7.8: PassArray.vb 2 ' Passing arrays and individual array elements to procedures. 3 4 Imports System.Windows.Forms 5 6 Module modPassArray 7 Dim output As String 8 9 Sub Main() 10 Dim array1 AsInteger() = NewInteger() {1, 2, 3, 4, 5} 11 Dim i As Integer 12 13 output = "EFFECTS OF PASSING ENTIRE ARRAY " & _ 14 "BY REFERENCE:" & vbCrLf & vbCrLf & _ 15 "The values of the original array are:" & vbCrLf 16 17 ' display original elements of array1 18For i = 0To array1.GetUpperBound(0) 19 output &= " " & array1(i) 20 Next 21 22 ModifyArray(array1) ' array is passed by reference 23 24 output &= vbCrLf & _ 25 "The values of the modified array are:" & vbCrLf 26 27 ' display modified elements of array1 28For i = 0To array1.GetUpperBound(0) 29 output &= " " & array1(i) 30 Next 31 PassArray.vb

  22. Multiplies the elements of arrayParameter by 2 32 output &= vbCrLf & vbCrLf & _ 33 "EFFECTS OF PASSING ARRAY ELEMENT " & _ 34 "BY VALUE:" & vbCrLf & vbCrLf & "array1(3) " & _ 35 "before ModifyElementByVal: " & array1(3) 36 37 ' array element passed by value 38 ModifyElementByVal(array1(3)) 39 40 output &= vbCrLf & "array1(3) after " & _ 41 "ModifyElementByVal: " & array1(3) 42 43 output &= vbCrLf & vbCrLf & "EFFECTS OF PASSING " & _ 44 "ARRAY ELEMENT BY REFERENCE: " & vbCrLf & vbCrLf & _ 45 "array1(3) before ModifyElementByRef: " & array1(3) 46 47 ' array element passed by reference 48 ModifyElementByRef(array1(3)) 49 50 output &= vbCrLf & "array1(3) after " & _ 51 "ModifyElementByRef: " & array1(3) 52 53 MessageBox.Show(output, "Passing Arrays", _ 54 MessageBoxButtons.OK, MessageBoxIcon.Information) 55 EndSub' Main 56 57 ' procedure modifies array it receives (note ByVal) 58Sub ModifyArray(ByVal arrayParameter AsInteger()) 59 Dim j AsInteger 60 61 For j = 0To arrayParameter.GetUpperBound(0) 62 arrayParameter(j) *= 2 63 Next 64 65 EndSub' ModifyArray 66 PassArray.vb

  23. 67 ' procedure modifies integer passed to it 68 ' original is not be modified (note ByVal) 69 Sub ModifyElementByVal(ByVal element AsInteger) 70 71 output &= vbCrLf & "Value received in " & _ 72 "ModifyElementByVal: " & element 73 element *= 2 74 output &= vbCrLf & "Value calculated in " & _ 75 "ModifyElementByVal: " & element 76 EndSub' ModifyElementByVal 77 78 ' procedure modifies integer passed to it 79 ' original is be modified (note ByRef) 80 Sub ModifyElementByRef(ByRef element AsInteger) 81 82 output &= vbCrLf & "Value received in " & _ 83 "ModifyElementByRef: " & element 84 element *= 2 85 output &= vbCrLf & "Value calculated in " & _ 86 "ModifyElementByRef: " & element 87 EndSub' ModifyElementByRef 88 89 EndModule' modPassArray PassArray.vb 訂正: Line 15 of Fig 7.2 (p. 250), Line 27 of Fig 7.3 (p. 252), Line 26 of Fig 7.5 (p.254), Line 16 of Fig 7.6 (p. 256): 將 “&=” 改為 “=”

  24. PassArray.vb

  25. 7.6 Passing Arrays: ByVal vs. ByRef • Visual Basic.NET • A variable that “stores” an object, such as an array, does not actually store the object itself • The variable stores a reference to the object • Location in memory where the object is already stored • ByVal • Causes the value of the argument to be copied to a local variable in the procedure • Changes to the local variable are reflected in the local copy of that variable, not in the original variable in the calling program • But if the argument is of a reference type, like an array, passing it ByVal actually passes it by reference, so changes to the object affect the original objects in the callers

  26. 7.6 Passing Arrays: ByVal vs. ByRef • ByRef • When an array is passed with ByRef the called procedure gains control over the passed reference itself • This allows the called procedure to replace the original reference in the object with another object or even Nothing

  27. Copies reference firstArray to variable firstArrayCopy, now they reference the same object Prints contents first to verify that FirstDouble indeed changes the array’s contents firstArray is passed to FirstDouble 1 ' Fig. 7.9: ArrayReferenceTest.vb 2 ' Testing the effects of passing array references using 3 ' ByVal and ByRef. 4 5 Module modArrayReferenceTest 6 7 Sub Main() 8 Dim i As Integer 9 10 ' declare array references 11 Dim firstArray As Integer() 12 Dim firstArrayCopy As Integer() 13 14 ' allocate firstArray and copy its reference 15 firstArray = New Integer() {1, 2, 3} 16 firstArrayCopy = firstArray 17 18 Console.WriteLine("Test passing array reference " & _ 19 "using ByVal.") 20 Console.Write("Contents of firstArray before " & _ 21 "calling FirstDouble: ") 22 23 ' print contents of firstArray 24For i = 0To firstArray.GetUpperBound(0) 25 Console.Write(firstArray(i) & " ") 26 Next 27 28 ' pass firstArray using ByVal 29 FirstDouble(firstArray) 30 31 Console.Write(vbCrLf & "Contents of firstArray after " & _ 32 "calling FirstDouble: ") 33 ArrayReferenceTest.vb

  28. Compares references firstArray and firstArrayCopy 34 ' print contents of firstArray 35 For i = 0To firstArray.GetUpperBound(0) 36 Console.Write(firstArray(i) & " ") 37 Next 38 39 ' test whether reference was changed by FirstDouble 40If firstArray Is firstArrayCopy Then 41 Console.WriteLine(vbCrLf & "The references are " & _ 42 "equal.") 43 Else 44 Console.WriteLine(vbCrLf & "The references are " & _ 45 "not equal.") 46 End If 47 48 ' declare array references 49 Dim secondArray AsInteger() 50 Dim secondArrayCopy AsInteger() 51 52 ' allocate secondArray and copy its reference 53 secondArray = NewInteger() {1, 2, 3} 54 secondArrayCopy = secondArray 55 56 Console.WriteLine(vbCrLf & "Test passing array " & _ 57 "reference using ByRef.") 58 Console.Write("Contents of secondArray before " & _ 59 "calling SecondDouble: ") 60 61 ' print contents of secondArray before procedure call 62 For i = 0To secondArray.GetUpperBound(0) 63 Console.Write(secondArray(i) & " ") 64 Next 65 66 ' pass secondArray using ByRef 67 SecondDouble(secondArray) 68 ArrayReferenceTest.vb

  29. Reference is passed ByVal Multiplies all the elements of the array by 2 Allocates a new array, and attempts to assign it’s reference to parameter array, attempting to overwrite reference firstArray in memory, but will fail because the reference was passed ByVal 69 Console.Write(vbCrLf & "Contents of secondArray " & _ 70 "after calling SecondDouble: ") 71 72 ' print contents of secondArray after procedure call 73 For i = 0To secondArray.GetUpperBound(0) 74 Console.Write(secondArray(i) & " ") 75 Next 76 77 ' test whether the reference was changed by SecondDouble 78 If secondArray Is secondArrayCopy Then 79 Console.WriteLine(vbCrLf & "The references are " & _ 80 "equal.") 81 Else 82 Console.WriteLine(vbCrLf & "The references are " & _ 83 "not equal.") 84 EndIf 85 86 EndSub' Main 87 88 ' procedure modifies elements of array and assigns 89 ' new reference (note ByVal) 90Sub FirstDouble(ByVal array AsInteger()) 91 Dim i AsInteger 92 93 ' double each element value 94 For i = 0To array.GetUpperBound(0) 95 array(i) *= 2 96 Next 97 98 ' create new reference and assign it to array 99 array = NewInteger() {11, 12, 13} 100 EndSub' FirstDouble 101 ArrayReferenceTest.vb

  30. Reference is passed ByRef Because the reference was passed with ByRef, the called procedure has the ability to modify what the reference actually points to 102 ' procedure modifies elements of array and assigns 103 ' new reference (note ByRef) 104Sub SecondDouble(ByRef array AsInteger()) 105 Dim i AsInteger 106 107 ' double contents of array 108 For i = 0To array.GetUpperBound(0) 109 array(i) *= 2 110 Next 111 112 ' create new reference and assign it to array 113 array = NewInteger() {11, 12, 13} 114 EndSub' SecondDouble 115 116 EndModule' modPassArray ArrayReferenceTest.vb Test passing array reference using ByVal. Contents of firstArray before calling FirstDouble: 1 2 3 Contents of firstArray after calling FirstDouble: 2 4 6 The references are equal. Test passing array reference using ByRef. Contents of secondArray before calling SecondDouble: 1 2 3 Contents of secondArray after calling SecondDouble: 11 12 13 The references are not equal.

  31. 7.7 Sorting Arrays • Sorting • Sorting data is one of the most popular computing applications • Sometimes, the simplest algorithms perform poorly • Bubble Sort (a.k.a. sinking sort) • Smaller values “bubble” their way to the top of the array, (i.e. toward the first element) • Larger values “sink” to the bottom of the array, (i.e. toward the end) • In general only n-1 passes are needed to sort an n-element array • The bubble sort is easy to program, but runs slowly • Becomes apparent when sorting large arrays

  32. Sorts the elements of it’s parameter sortArray The nested For/Next structure performs the sort This inner loop controls the comparisons and swapping, if necessary, of the elements during each pass Gets called by BubbleSort to transpose two of the array elements 1 ' Fig. 7.10: BubbleSort.vb 2 ' Procedures for sorting an integer array. 3 4 Module modBubbleSort 5 6 ' sort array using bubble sort algorithm 7Sub BubbleSort(ByVal sortArray As Integer()) 8 Dim pass, i As Integer 9 10For pass = 1To sortArray.GetUpperBound(0) 11 12For i = 0To sortArray.GetUpperBound(0) - 1 13 14 If sortArray(i) > sortArray(i + 1) Then 15 Swap(sortArray, i) 16 End If 17 18 Next 19 20 Next 21 22 EndSub' BubbleSort 23 24 ' swap two array elements 25Sub Swap(ByVal swapArray AsInteger(), _ 26 ByVal first AsInteger) 27 28 Dim hold AsInteger 29 30 hold = swapArray(first) 31 swapArray(first) = swapArray(first + 1) 32 swapArray(first + 1) = hold 33 EndSub' Swap 34 35 EndModule' modBubbleSort BubbleSort.vb

  33. 1 ' Fig. 7.11: BubbleSortTest.vb 2 ' Program creates random numbers and sorts them. 3 4 Imports System.Windows.Forms 5 6 PublicClass FrmBubbleSort 7 Inherits System.Windows.Forms.Form 8 9 ' buttons 10 FriendWithEvents cmdCreate As Button 11 FriendWithEvents cmdSort As Button 12 13 ' labels 14 FriendWithEvents lblOriginal As Label 15 FriendWithEvents lblSorted As Label 16 17 ' textboxes 18 FriendWithEvents txtOriginal As TextBox 19 FriendWithEvents txtSorted As TextBox 20 21 ' Visual Studio .NET generated code 22 23 Dim array As Integer() = New Integer(9) {} 24 25 ' creates random generated numbers 26 Private Sub cmdCreate_Click(ByVal sender As System.Object, _ 27 ByVal e As System.EventArgs) Handles cmdCreate.Click 28 29 Dim output As String 30 Dim randomNumber As Random = New Random() 31 Dim i AsInteger 32 33 txtSorted.Text = "" 34 BubbleSortTest.vb

  34. 35 ' create 10 random numbers and append to output 36 For i = 0To array.GetUpperBound(0) 37 array(i) = randomNumber.Next(100) 38 output &= array(i) & vbCrLf 39 Next 40 41 txtOriginal.Text = output ' display numbers 42 cmdSort.Enabled = True' enables cmdSort button 43 EndSub ' cmdCreate_Click 44 45 ' sorts randomly generated numbers 46 Private Sub cmdSort_Click(ByVal sender As System.Object, _ 47 ByVal e As System.EventArgs) Handles cmdSort.Click 48 49 Dim output As String 50 Dim i As Integer 51 52 ' sort array 53 modBubbleSort.BubbleSort(array) 54 55 ' creates string with sorted numbers 56 For i = 0 To array.GetUpperBound(0) 57 output &= array(i) & vbCrLf 58 Next 59 60 txtSorted.Text = output ' display numbers 61 cmdSort.Enabled = False 62 EndSub' cmdSort_Click 63 64 EndClass' FrmBubbleSort BubbleSortTest.vb

  35. BubbleSortTest.vb

  36. 7.8 Searching Arrays: Linear Search and Binary Search • Searching • The process of locating a particular element value in an array • Linear Search • Simple searching technique • Works well for small or unsorted arrays • On average half the elements of the array will be compared • Binary Search • If array is sorted, binary search is more efficient, but also a more complex technique • After each comparison, the binary search algorithm eliminates half of the elements in the array • The search continues till the search key is equal to the middle element of a subarray, or till the subarray consists of only one element that is not equal to the search key. • The maximum number of comparisons in a binary search is the exponent of the first power of 2 that is greater than the number of elements being searched

  37. Compares each element of the array with a search key If the search key is not found, the procedure returns –1, a non-valid index number 1 ' Fig. 7.12: LinearSearch.vb 2 ' Linear search of an array. 3 4 Module modLinearSearch 5 6 ' iterates through array 7 Function LinearSearch(ByVal key AsInteger,_ 8 ByVal numbers AsInteger()) AsInteger 9 10 Dim n AsInteger 11 12 ' structure iterates linearly through array 13For n = 0 To numbers.GetUpperBound(0) 14 15 If numbers(n) = key Then 16 17 Return n 18 End If 19 20 Next 21 22Return-1 23 End Function ' LinearSearch 24 25 End Module ' modLinearSearch LinearSearch.vb

  38. 1 ' Fig. 7.13: LinearSearchTest.vb 2 ' Linear search of an array. 3 4 Imports System.Windows.Forms 5 6 PublicClass FrmLinearSearchTest 7 Inherits System.Windows.Forms.Form 8 9 ' buttons 10 FriendWithEvents cmdSearch As Button 11 FriendWithEvents cmdCreate As Button 12 13 ' text boxes 14 FriendWithEvents txtInput As TextBox 15 FriendWithEvents txtData As TextBox 16 17 ' labels 18 FriendWithEvents lblEnter As Label 19 FriendWithEvents lblResult As Label 20 21 ' Visual Studio .NET generated code 22 23 Dim array1 As Integer() = NewInteger(19) {} 24 25 ' creates random data 26 PrivateSub cmdCreate_Click(ByVal sender As System.Object, _ 27 ByVal e As System.EventArgs) Handles cmdCreate.Click 28 29 Dim output AsString 30 Dim randomNumber As Random = New Random() 31 Dim i AsInteger 32 33 output = "Index" & vbTab & "Value" & vbCrLf 34 LinearSearchTest.vb

  39. 35 ' creates string containing 11 random numbers 36 For i = 0To array1.GetUpperBound(0) 37 array1(i) = randomNumber.Next(1000) 38 output &= i & vbTab & array1(i) & vbCrLf 39 Next 40 41 txtData.Text = output ' displays numbers 42 txtInput.Text = "" ' clear search key text box 43 cmdSearch.Enabled = True' enable search button 44 EndSub' cmdCreate_Click 45 46 ' searches key of element 47 PrivateSub cmdSearch_Click(ByVal sender As System.Object, _ 48 ByVal e As System.EventArgs) Handles cmdSearch.Click 49 50 ' if search key text box is empty, display 51 ' message and exit procedure 52 If txtInput.Text = "" Then 53 MessageBox.Show("You must enter a search key.") 54 Exit Sub 55 EndIf 56 57 Dim searchKey AsInteger = Convert.ToInt32(txtInput.Text) 58 Dim element AsInteger = LinearSearch(searchKey, array1) 59 60 If element <> -1Then 61 lblResult.Text = "Found Value in index " & element 62 Else 63 lblResult.Text = "Value Not Found" 64 EndIf 65 66 EndSub' cmdSearch_Click 67 68 EndClass' FrmLinearSearch LinearSearchTest.vb

  40. LinearSearchTest.vb

  41. 1 ' Fig. 7.14: BinarySearchTest.vb 2 ' Demonstrating binary search of an array. 3 4 Imports System.Windows.Forms 5 6 PublicClass FrmBinarySearch 7 Inherits System.Windows.Forms.Form 8 9 ' labels 10 FriendWithEvents lblEnterKey As Label 11 FriendWithEvents lblResult As Label 12 FriendWithEvents lblResultOutput As Label 13 FriendWithEvents lblDisplay As Label 14 FriendWithEvents lblIndex As Label 15 FriendWithEvents lblIndexes As Label 16 17 ' button 18 FriendWithEvents cmdFindKey As Button 19 20 ' text box 21 FriendWithEvents txtInput As TextBox 22 23 ' Visual Studio .NET generated code 24 25 Dim array1 AsInteger() = New Integer(14) {} 26 27 ' FrmBinarySearch initializes array1 to ascending values 28 ' 0, 2, 4, 6, ..., 28 when first loaded 29 PrivateSub FrmBinarySearch_Load(ByVal sender As System.Object, _ 30 ByVal e As System.EventArgs) Handles MyBase.Load 31 32 Dim i AsInteger 33 BinarySearchTest.vb

  42. Receives two arguments, the array to search, and the search key 34 For i = 0To array1.GetUpperBound(0) 35 array1(i) = 2 * i 36 Next 37 38 End Sub ' FrmBinarySearch_Load 39 40 ' event handler for cmdFindKey button 41 PrivateSub cmdFindKey_Click(ByVal sender As System.Object, _ 42 ByVal e As System.EventArgs) Handles cmdFindKey.Click 43 44 Dim searchKey AsInteger = Convert.ToInt32(txtInput.Text) 45 46 lblDisplay.Text = "" 47 48 ' perform binary search 49 Dim element AsInteger = BinarySearch(array1, searchKey) 50 51 If element <> -1Then 52 lblResultOutput.Text = "Found value in element " & element 53 Else 54 lblResultOutput.Text = "Value not found" 55 End If 56 57 End Sub ' cmdFindKey_Click 58 59 ' performs binary search 60Function BinarySearch(ByVal array AsInteger(), _ 61 ByVal key AsInteger) AsInteger 62 63 Dim low AsInteger = 0' low index 64 Dim high AsInteger = array.GetUpperBound(0) ' high index 65 Dim middle AsInteger' middle index 66 BinarySearchTest.vb

  43. Calculates the middle element of the array If middle matches key, then middle is returned If key does not match middle, then the low or high index is adjusted so that a smaller subarray can be searched 67 While low <= high 68 middle = (low + high) \ 2 69 70 ' the following line displays part 71 ' of the array being manipulated during 72 ' each iteration of loop 73 BuildOutput(low, middle, high) 74 75If key = array(middle) Then ' match 76 Return middle 77ElseIf key < array(middle) Then' search low end 78 high = middle - 1' of array 79Else 80 low = middle + 1 81 End If 82 83 End While 84 85 Return-1' search key not found 86 End Function ' BinarySearch 87 88 Sub BuildOutput(ByVal low AsInteger, _ 89 ByVal middle AsInteger, ByVal high AsInteger) 90 91 Dim i AsInteger 92 BinarySearchTest.vb

  44. 93 For i = 0 To array1.GetUpperBound(0) 94 95 If i < low OrElse i > high Then 96 lblDisplay.Text &= " " 97 ElseIf i = middle Then ' mark middle element in output 98 lblDisplay.Text &= String.Format("{0:D2}", _ 99 array1(i)) & "* " 100 Else 101 lblDisplay.Text &= String.Format("{0:D2}", _ 102 array1(i)) & " " 103 End If 104 105 Next i 106 107 lblDisplay.Text &= vbCrLf 108 End Sub ' BuildOutput 109 110 EndClass' FrmBinarySearch BinarySearchTest.vb

  45. BinarySearchTest.vb

  46. 7.9 Multidimensional Rectangular and Jagged Arrays • Multidimensional arrays (multiple-subscripted) • Require two or more indices to identify particular elements • Rectangular arrays • Two indices, first identifies the element’s row, the second the elements column • A rectangular two-dimensional array with m rows and n columns is called an m-by-n array • Jagged arrays • Jagged arrays are maintained as arrays of arrays • Rows in jagged arrays can be of different lengths

  47. 7.9 Multidimensional Rectangular and Jagged Arrays Column 0 Column 1 Column 2 Column 3 a(0, 0) a(0, 1) a(0, 2) a(0, 3) Row 0 Row 1 a(1, 0) a(1, 1) a(1, 2) a(1, 3) a(2, 0) a(2, 1) a(2, 2) a(2, 3) Row 2 Column index Row index (or subscript) Array name Fig. 7.15 Two-dimensional array with three rows and four columns.

  48. Allocates array1 with six initializers in two sublists The declaration and allocation of array2 creates a jagged array of 3 arrays Traverses the array in two dimensions 1 ' Fig. 7.16: MultidimensionalArrays.vb 2 ' Initializing multi-dimensional arrays. 3 4 Imports System.Windows.Forms 5 6 Module modMultidimensionalArrays 7 8 Sub Main() 9 Dim output AsString 10 Dim i, j AsInteger 11 12 ' create rectangular two-dimensional array 13 Dim array1 AsInteger(,) 14 array1 = New Integer(,) {{1, 2, 3}, {4, 5, 6}} 15 16 ' create jagged two-dimensional array 17Dim array2 AsInteger()()= New Integer(2)() {} 18 19 array2(0) = NewInteger() {1, 2} 20 array2(1) = NewInteger() {3} 21 array2(2) = NewInteger() {4, 5, 6} 22 23 output = "Values in array1 by row are " & vbCrLf 24 25For i = 0To array1.GetUpperBound(0) 26 27 For j = 0To array1.GetUpperBound(1) 28 output &= array1(i, j) & " " 29 Next 30 31 output &= vbCrLf 32 Next 33 MultidimensionalArrays.vb

  49. In a jagged two-dimensional array, the second dimension is actually the first dimension of a separate array 34 output &= vbCrLf & "Values in array2 by row are " & _ 35 vbCrLf 36 37 For i = 0To array2.GetUpperBound(0) 38 39For j = 0To array2(i).GetUpperBound(0) 40 output &= array2(i)(j) & " " 41 Next 42 43 output &= vbCrLf 44 Next 45 46 MessageBox.Show(output, _ 47 "Initializing Multi-Dimensional Arrays", _ 48 MessageBoxButtons.OK, MessageBoxIcon.Information) 49 End Sub ' Main 50 51 End Module ' modMultidimensionalArrays MultidimensionalArrays.vb

  50. 1 ' Fig 7.17: JaggedArray.vb 2 ' Jagged two-dimensional array example. 3 4 Imports System.Windows.Forms 5 6 Module modJaggedArray 7 Dim lastStudent, lastExam As Integer 8 Dim output As String 9 10 Sub Main() 11 Dim i As Integer 12 13 ' jagged array with 3 rows of exam scores 14 Dim gradeArray AsInteger()() = NewInteger(2)() {} 15 16 ' allocate each row with 4 student grades 17 gradeArray(0) = NewInteger() {77, 68, 86, 73} 18 gradeArray(1) = NewInteger() {98, 87, 89, 81} 19 gradeArray(2) = NewInteger() {70, 90, 86, 81} 20 21 ' upper bounds for array manipulations 22 lastStudent = gradeArray.GetUpperBound(0) 23 lastExam = gradeArray(0).GetUpperBound(0) 24 25 output = "Students \ Exams" & vbCrLf 26 27 ' build output string 28 BuildString(gradeArray) 29 output &= vbCrLf & vbCrLf & "Lowest grade: " & _ 30 Minimum(gradeArray) & vbCrLf & "Highest grade: " & _ 31 Maximum(gradeArray) & vbCrLf 32 JaggedArray.vb

More Related