當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


VB.NET Array BinarySearch()用法及代碼示例

BinarySearch() 方法用於從排序數組中搜索指定項。

用法:

Function BinarySearch(ByVal arr() as object, ByVal num as object) as Integer

參數:

  • Arr:它是指定的排序數組。
  • Num:要搜索的指定號碼。

返回值:它返回搜索項的索引。如果該項目在指定的數組中沒有找到,那麽它將返回一個負值。

程序/源代碼:

下麵給出了演示 Array 類的 BinarySearch() 方法的源代碼。給定的程序已成功編譯並執行。

'VB.NET program to demonstrate the BinarySearch() 
'method of Array class.

Imports System

Module Module1
    Sub Main()
        Dim index As Integer
        Dim arr() As Integer = {10, 20, 30, 40, 50}

        index = Array.BinarySearch(arr, 30)

        If (index < 0) Then
            Console.WriteLine("Item not found")
        Else
            Console.WriteLine("Item {0} find at index:{1}", 30, index)
        End If
    End Sub
End Module

輸出:

Item 30 find at index:2
Press any key to continue . . .

說明:

在上麵的程序中,我們創建了一個包含 Main() 函數的模塊 Module1。 Main() 函數是程序的入口點。

在 Main() 函數中,我們創建了一個包含 5 個元素的數組 arr。然後我們使用Array類的BinarySearch()方法搜索第30項並返回索引。之後,我們在控製台屏幕上打印指定項目的索引。



相關用法


注:本文由純淨天空篩選整理自 VB.Net program to demonstrate the BinarySearch() method of Array class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。