Two-point search-vb.net

Source: Internet
Author: User

Module Module1

Sub Main ()
Dim Array (999) as Integer
Dim Searchvalue as Integer
Dim ValueIndex as Integer
Dim Rnd as New Random ()

For i as Integer = 0 to UBound (array)
If (i = 0) Then
Array (i) = rnd. Next (10)
Else
Array (i) = rnd. Next (Array (i-1), Array (i-1) + 10)
End If
Console.WriteLine ("Array (" & I & ") =" & Array (i))
Next I

Console.WriteLine (VbCrLf & "Please enter an integer between 1~100:")
Searchvalue = Console.ReadLine ()

ValueIndex = Find (array, searchvalue)
If (ValueIndex <>-1) Then
Console.WriteLine ("Find success! Element at index ("& ValueIndex &")
Else
Console.WriteLine ("Find failed! ")
End If

Console.readkey ()
End Sub

Function Find (ByVal array () As Integer, ByVal searchvalue As Integer) As Integer
Dim result as Boolean
Dim ValueIndex as Integer
Dim StartIndex, EndIndex as Integer

StartIndex = 0
EndIndex = UBound (array)
result = BinarySearch (array, Searchvalue, StartIndex, EndIndex, ValueIndex)

Return IIf (result, ValueIndex,-1)
End Function

Function BinarySearch (ByVal array () As Integer, ByVal searchvalue As Integer, ByRef startIndex As Integer, ByRef endIndex As Integer, ByRef valueindex as Integer) as Boolean
If (array is nothing Or array. Length = 0) Then
Return False
End If

Dim Midindex as Integer
Midindex = math.ceiling ((startIndex + endIndex)/2)
If (Array (midindex) = Searchvalue) Then
ValueIndex = Midindex
Return True
End If

If (Array (Midindex) < Searchvalue) Then
StartIndex = Midindex + 1
EndIndex = EndIndex
Else
StartIndex = StartIndex
EndIndex = midIndex-1
End If

Return BinarySearch (Array, Searchvalue, StartIndex, EndIndex, ValueIndex)
End Function
End Module

Two-point search-vb.net

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.