Transcript Ch7

Chapter 7
Arrays
Chapter 7 - Visual Basic
Schneider
1
Outline and Objective
• Arrays in Visual Basic
• One-dimensional arrays
• Control arrays
• Two-dimensional arrays
• Searching
• Sorting
Chapter 7 - Visual Basic
Schneider
2
Array verses Simple Variable
• Simple variable is used to store a single
value.
• Array variable is used to represent many
values of the same type with one variable
name.
Chapter 7 - Visual Basic
Schneider
3
Elements of an Array
• Array Name: A valid variable name for the
structure.
• Subscript or Index : A value that refers to a
particular array element.
• Element or Subscripted variable: An
individual data item within an array.
Chapter 7 - Visual Basic
Schneider
4
Array Declaration
• Syntax
Dim arrayName(m To n) As varType
where m and n are integers
• Examples
– Dim month(1 To 12) As String
– Dim population(1987 To 2003) As Single
– Dim students(1 To 30) As String
Chapter 7 - Visual Basic
Schneider
5
The Dim Statement
• Used to declare an array
• A Dim statement must occur before the first
reference to the array elements.
Chapter 7 - Visual Basic
Schneider
6
Initializing an Array
Private Sub cmdWhoWon_Click()
Dim teamName(1 To 4) As String
Dim n As Integer
teamName(1) = "Red Sox"
teamName(2) = "Giants"
teamName(3) = "White Sox"
teamName(4) = "Cubs"
n = Val(txtNumber.Text)
picWinner.Print "The "; teamName(n); " won World Series #"; n
End Sub
Chapter 7 - Visual Basic
Schneider
7
Array teamName()
Array Name
Dim teamName( 1 To 4) As String
Red Sox
Giants
White Sox
Cubs
teamName(1)
Index
Chapter 7 - Visual Basic
Schneider
8
Initializing an Array by Reading from a File
Dim student (1 To 30) As String
Dim count As Integer
Open “STUDENTS.TXT” For Input As #1
For count = 1 To 30
Input #1, student(count)
Next count
Chapter 7 - Visual Basic
Schneider
9
Adding Up Elements in an Array
Dim score(1 To 30) As Single, student(1 To 30) As String
Dim count As Integer, average as Integer, sum As Integer
Open “STUDENT.TXT” For Input As #1
For count = 1 To 30
Input #1, student(count), score(count)
Next count
sum = 0
For count = 1 To 30
sum = sum + score(count)
Next count
average = sum/30
Chapter 7 - Visual Basic
Schneider
10
Parallel Arrays
• Two arrays are said to be parallel if
subscripted variables having the same
subscript are related.
Chapter 7 - Visual Basic
Schneider
11
Example of Parallel Arrays
Dim nom(1 To 8) As String, score(1 To 8) As Integer
Dim student As Integer
Open “SCORE.TXT” For Input As #1
For student = 1 To 8
Input #1, nom(student), score(student)
Next student
Close #1
Chapter 7 - Visual Basic
Schneider
12
Form_Load()
• Use it to Initialize Form Level variables
• Use it to initialize Form Level Arrays
• Use it to Dim Dynamic Arrays
Chapter 7 - Visual Basic
Schneider
13
Dynamic Arrays
• ReDim can only be used inside a procedure
• Defines or dimensions a Dynamic array
– ReDim arrayName (m To n) as varType
– m, n can be a variables or expressions
• Use Dim in General Declaration as
– Dim arrayName() as varType
– Cannot be used till you ReDim it in a procedure
Chapter 7 - Visual Basic
Schneider
14
Ordered Array
• An array is ordered if its values are in either
ascending or descending order.
• For string arrays, the ANSI table is used to
evaluate the “less than or equal to”
condition.
Chapter 7 - Visual Basic
Schneider
15
Merging two ordered arrays
1.Compare the two first elements of the first and second
arrays.
A. If one name alphabetically precedes the other, copy
it onto the third list and cross it off the original
array.
B. If the names are the same, copy the name onto the
third list and cross out the name from both arrays.
2. Repeat Step 1 with the new name in the array until you
reach the end of either array.
3. Copy the names from the remaining array onto the third
array.
Chapter 7 - Visual Basic
Schneider
16
Passing an Array
• An array can be passed to another procedure by
reference.
• Example:
Private Sub cmddisplay_Click()
'Pass array to subprogram and function
Dim score(1 To 5) As Integer
Call FillArray(score())
picAverage.Print ”Average is"; Sum(score()) / 5
End Sub
Chapter 7 - Visual Basic
Schneider
17
Array Score is passed to a Sub procedure
Private Sub FillArray(s() As Integer)
' Fill array with scores
s(1) = 85
s(2) = 92
This array is pointing to the same
s(3) = 75
location as array score
s(4) = 68
s(5) = 84
End Sub
Chapter 7 - Visual Basic
Schneider
18
Array score is passed to a Function
Private Function Sum(s() As Integer) As Integer
Dim total As Integer, index As Integer
'Add up scores
total = 0
For index = 1 To 5
total = total + s(index)
Next index
Sum = total
End Function
Chapter 7 - Visual Basic
Schneider
19
Sorting
• A common practice involving arrays is to
sort the elements of the array in either
ascending or descending order.
• Sorting techniques
– Bubble Sort
– Shell Sort
Chapter 7 - Visual Basic
Schneider
20
Bubble Sort
• The bubble sort involves comparing
adjacent elements and swapping the values
of those elements when they are out of
order.
• One complete time through an array is
called a pass.
Chapter 7 - Visual Basic
Schneider
21
Bubble Sort
For passNum = 1 To 4
For index = 1 To 5 - passNum
If name(index) > name(index + 1) Then
Call SwapData(name(), index)
End If
Next index
Next passNum
Chapter 7 - Visual Basic
Schneider
22
Swapping two variables
Private Sub SwapData (A() As String, index As Integer)
Dim temp As String
temp = A(index)
A(index) = A(index + 1)
A(index + 1) = temp
End Sub
Chapter 7 - Visual Basic
Schneider
23
Bubble Sort
• The number of passes used to sort the elements in
an array is equal to the number of elements in the
array less 1.
• Bubble sort works well for sorting small arrays,
but is often too slow for very large ones.
Chapter 7 - Visual Basic
Schneider
24
Shell Sort
• Similar to the bubble sort
• Instead of comparing and swapping adjacent
elements A(count) and A(count+1), Shell sort
compares and swaps non-adjacent elements
A(count) and A(count + Gap), where Gap starts at
roughly half the size of the array
Chapter 7 - Visual Basic
Schneider
25
Shell Sort
• At the end of each pass, if no elements have been
swapped in the current pass, then Gap is halved
for the next pass.
• Eventually, Gap becomes one, and adjacent
elements are compared and swapped as necessary.
Chapter 7 - Visual Basic
Schneider
26
Shell Sort
gap = Int(numParts / 2)
Do While gap >= 1
Do
doneFlag = True
For index = 1 To numParts - gap
If part(index) > part(index + gap) Then
Call Swap(part(index), part(index + gap)
doneFlag = False
End If
Next index
Loop Until doneFlag = True
gap = Int(gap / 2)
'Halve the length of the gap
Loop
Chapter 7 - Visual Basic
Schneider
27
Efficiency of Bubble and Shell sort
(average number of comparisons)
Array Elements
Bubble Sort
Shell Sort
5
10
15
15
25
30
100
500
105
300
435
4,950
124,750
115
302
364
2,638
22,517
Chapter 7 - Visual Basic
Schneider
28
Ordered Array
• An array is ordered if its values are in either
ascending or descending order.
• For string arrays, ANSI values are used to
evaluate the “less than or equal to”
condition.
Chapter 7 - Visual Basic
Schneider
29
Searching Arrays
• The process of finding the position of a value in an
array is called searching
• A sequential search examines each element,
beginning with the first, until the specified value is
found or the end of the array is reached
Chapter 7 - Visual Basic
Schneider
30
Example of a Sequential Search
Dim nom(1 To 15) As String, index As Integer, foundFlag As Boolean
Do While (index <= 15) And (Not foundFlag)
If nom(index) = “Fred” Then
foundFlag = True
Else
index = index + 1
End If
Loop
picOutput.Print “Fred is located at position“; index
Chapter 7 - Visual Basic
Schneider
31
Sequential Search
• Useful for small arrays.
• Very inefficient for large arrays (for
example, names in a telephone book).
• For any size array, if the array is ordered,
the more efficient binary search can be
used.
Chapter 7 - Visual Basic
Schneider
32
Binary Search
• In a binary search, an ordered array is
repeatedly divided in half. The half not
containing the target value is ignored.
Chapter 7 - Visual Basic
Schneider
33
Binary Search
Private Sub BinarySearch(corp As String, result As String)
Dim foundFlag As Boolean, first as Integer, last as Integer
first = 1
last = numFirms
Do While (first <= last) And (foundFlag = False)
middle = Int((first + last) / 2)
Select Case UCase(firm(middle))
Case corp
foundFlag = True
Case Is > corp
last = middle - 1
Case Is < corp
first = middle + 1
End Select
Loop ‘continued on next slide
Chapter 7 - Visual Basic
Schneider
34
Binary Search (continued)
If foundFlag = True Then
result = "found”
Else
result = "not found
End If
End Sub
Chapter 7 - Visual Basic
Schneider
35
Two-Dimensional Arrays
• Store values as a table, grouped into rows
and columns.
• The first subscript of a two-dimensional
array refers to the row and the second
subscript to the column.
Chapter 7 - Visual Basic
Schneider
36
Declaration of Two-Dimensional Array
• Syntax:
– Dim arrayName(m1 To m2, n1 To n2) As varType
• Example:
– Dim rm(1 To 4, 1 To 4) As Single
column
row
Chapter 7 - Visual Basic
Schneider
37
Example of a two-dimensional array:
rm(1 To 4, 1 To 4)
Chicago
Los Angeles
New York
Philadelphia
Chicago
Los Angeles
New York
0
2054
802
736
2054
0
2786
2706
802
2786
0
100
rm (2,2)
Chapter 7 - Visual Basic
Schneider
Philadelphia
738
2706
100
0
rm (3,4)
38
Example of Input File
0, 2054, 802, 738
2054, 0, 2786, 2706
802, 2786, 0, 100
738, 2706, 100, 0
Chapter 7 - Visual Basic
Schneider
39
Manipulating a Two-Dimensional Array
• Use nested For … Next loops to assign or access
elements of a two-dimensional array.
• Example:
For row = 1 To 4
For col = 1 To 4
Input #1, rm(row, col)
Next col
Next row
Chapter 7 - Visual Basic
Schneider
40
Examples: How many elements?
•
•
•
•
•
•
•
Dim rm(1 To 4) As Single
Dim rm(4, 1 To 4) As Single
Dim rm(1 To 4, 1 To 4) As Single
Dim rm(4, 1 To 4) As Single
Dim rm(0 To 3, 97 To 100)
Dim rm (-5 To -3, 5 To 5)
Dim (-3 To -5)
Chapter 7 - Visual Basic
Schneider
41