9.3 數(shù)組應(yīng)用例題
1. 排序
例5-3 選擇排序法、直接排序法
Option Explicit
Option Base 1
Private Sub CmdSort_Click()
Dim Sort(10) As Integer, Temp As Integer
Dim I As Integer, J As Integer
Randomize
For I = 1 To 10
Sort(I) = Int(Rnd * (100 - 1)) + 1
Text1 = Text1 & Str(Sort(I))
Next I
For I = 1 To 9
For J = I + 1 To 10
If Sort(I) > Sort(J) Then
Temp = Sort(I)
Sort(I) = Sort(J)
Sort(J) = Temp
End If
Next J
Text2 = Text2 & Str(Sort(I))
Next I
Text2 = Text2 & Str(Sort(10))
End Sub
Option Explicit
Option Base 1
Private Sub CmdSort_Click()
Dim Sort(10) As Integer, Temp As Integer
Dim I As Integer, J As Integer
Dim Pointer As Integer
Randomize
For I = 1 To 10
Sort(I) = Int(Rnd * (100 - 1)) + 1
Text1 = Text1 & Str(Sort(I))
Next I
For I = 1 To 9
Pointer = I
For J = I + 1 To 10
If Sort(Pointer) > Sort(J) Then
Pointer = J
End If
Next J
If I <> Pointer Then
Temp = Sort(I)
Sort(I) = Sort(Pointer)
Sort(Pointer) = Temp
End If
Text2 = Text2 & Str(Sort(I))
Next I
Text2 = Text2 & Str(Sort(10))
End Sub
2. 查找
例:5-4 順序查找程序
先介紹For Each -next 結(jié)構(gòu)的語句:
Option Explicit
Option Base 1
Dim Search As Variant
Private Sub Cmd生成數(shù)組_Click()
Dim I As Integer, Element As Variant
Search = Array(34, 12, 56, 81, 59, 83, 91, 26, 47)
For Each Element In Search'for each-next 結(jié)構(gòu)語句
Text1 = Text1 & Str(Element)
Next Element
End Sub
Private Sub Cmd查找_Click()
Dim I As Integer, Find As Integer
Text2 = ""
Find = InputBox("輸入要查找的數(shù)")
For I = 1 To UBound(Search)
If Search(I) = Find Then Exit For
Next I
If I <= UBound(Search) Then
Text2 = "要查找的數(shù)" & Str(Search(I)) & "是Search(" & Str(I) & ")"
Else
Text2 = "在數(shù)列中沒有找到" & Str(Find)
End If
End Sub
例 5-5 二分查找程序:
Option Explicit
Option Base 1
Dim Search As Variant
Private Sub Cmd二分查找_Click()
Dim Left As Integer, Right As Integer
Dim Mid As Integer, Flg As Boolean
Dim Find As Integer
Find = InputBox("輸入要查找的數(shù)")
Left = 1: Right = UBound(Search)
Flg = False
Do While Left <= Right
Mid = (Left + Right) / 2
If Search(Mid) = Find Then
Flg = True
Exit Do
ElseIf Find > Search(Mid) Then
Left = Mid + 1
Else
Right = Mid - 1
End If
Loop
If Flg Then
Text2 = "要查找的數(shù)" & Str(Find) & "在Search(" & Str(Mid) & ")中"
Else
Text2 = Str(Find) & "不在數(shù)組中"
End If
End Sub
Private Sub Cmd生成數(shù)據(jù)_Click()
Dim V As Variant
Search = Array(12, 17, 23, 28, 30, 39, 41, 46, 57, 61, 78, 83, 85, 89, 93)
For Each V In Search
Text1 = Text1 & Str(V)
Next V
End Sub
北京 | 天津 | 上海 | 江蘇 | 山東 |
安徽 | 浙江 | 江西 | 福建 | 深圳 |
廣東 | 河北 | 湖南 | 廣西 | 河南 |
海南 | 湖北 | 四川 | 重慶 | 云南 |
貴州 | 西藏 | 新疆 | 陜西 | 山西 |
寧夏 | 甘肅 | 青海 | 遼寧 | 吉林 |
黑龍江 | 內(nèi)蒙古 |