在 Visual Basic 中執行二元搜尋的程式可以使用下面的範例代碼。這個函數接受一個有序的陣列和一個要搜尋的目標值,然後回傳目標值在陣列中的索引位置。如果目標值不存在於陣列中,則回傳 -1。
這裡是二元搜尋的 Visual Basic 實現:
Module BinarySearchModule
Function BinarySearch(ByVal arr() As Integer, ByVal target As Integer) As Integer
Dim low As Integer = 0
Dim high As Integer = arr.Length - 1
Dim mid As Integer
While low <= high
mid = low + (high - low) \ 2
If arr(mid) = target Then
Return mid
ElseIf arr(mid) < target Then
low = mid + 1
Else
high = mid - 1
End If
End While
Return -1 ' 如果未找到目標值
End Function
Sub Main()
Dim arr() As Integer = {1, 10, 12, 16, 22, 30, 36, 52, 68, 72, 85, 91, 96}
Dim target As Integer = 30 ' 設定想要搜尋的目標值
Dim result As Integer = BinarySearch(arr, target)
If result <> -1 Then
Console.WriteLine("元素 {0} 在陣列的索引位置是: {1}", target, result)
Else
Console.WriteLine("陣列中找不到元素 {0}", target)
End If
Console.ReadLine() ' 等待用戶響應,然後結束
End Sub
End Module
將上面的代碼貼到 Visual Basic 的 IDE 或編輯器中,並運行它。這將執行 Main 方法,其中包含一個有序陣列和一個目標值。該程序會使用 BinarySearch 函數來搜尋目標值並打印結果。
記得,二元搜尋的前提是陣列已經是有序的。如果陣列是無序的,則需要先進行排序,然後才能使用二元搜尋。