プロが教える店舗&オフィスのセキュリティ対策術

今VB.netで二分探索のプログラムを作ろうとしています。
普通の二分探索のプログラムを作ることはできたのですが再帰を使っての二分探索を行うプログラムを作ろうとして悩んでいます。

再帰を行うために普通の二分探索の一部をプロシージャとして分けるところまではできました。再帰をどこに入れればいいのか分からないのですがご教授願えますでしょうか?

よろしくお願いします。下に現在できているコードを載せておきます。



Private Sub butSarch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butSarch.Click
'捜索
Dim intS, intCnt, intL, intR As Integer
intS = InputBox("探索したい数値を入力してください", "数値入力")
intCnt = 1
intL = 0
intR = 9

fucTansaku(intS, intCnt, intL, intR)


End Sub
Private Function fucTansaku(ByVal intS2 As Integer, ByVal intCnt2 As Integer, ByVal intL2 As Integer, ByVal intR2 As Integer) As Integer
Dim intM As Integer

intM = (intL2 + intR2) \ 2
Do While intL2 <= intR2
If intA(intM) = intS2 Then
Exit Do
End If
If intA(intM) < intS2 Then
intL2 = intM + 1
Else
intR2 = intM - 1
End If
intM = (intL2 + intR2) \ 2
intCnt2 = intCnt2 + 1
Loop

If intL2 <= intR2 Then
MsgBox(intCnt2 & "回目の探索で見つかりました", MsgBoxStyle.OkOnly, "結果")
Else
MsgBox("見つかりませんでした", MsgBoxStyle.OkOnly, "結果")
End If

End Function

A 回答 (1件)

Option Explicit On


Option Strict On
Option Compare Binary
Option Infer Off

'フォームに表示される内容がどうであるかと
'二分検索のプログラムは分けた方がすっきりするだろう。
'後者のみを作ってみた。

'メモ:アルゴリズムの都合上,その番号は0から探し始めて最初に見つかる番号とは限らない...と思う。


Public Class Q4631055A
Private arr As Integer()
Public Shared Sub Main()

Dim arr1 As Integer() = New Integer(){1,3,5,11,12,13,17,22,25,28}

Dim a As Q4631055A = New Q4631055A(arr1)
System.Console.WriteLine(a.FindIndex(13)) '5(0から数え始めるから)
System.Console.WriteLine(a.FindIndex(14)) '-1(存在しなかった場合)


End Sub

Public Sub New(arr1 As Integer())
arr = arr1
End Sub


Public Function FindIndex(x As Integer) As Integer

Return SubFind(x,0,arr.length - 1)

End Function

Private Function SubFind(x As Integer,left As Integer,right As Integer) As Integer

Dim center As Integer = Integer.Parse(System.Math.Floor((left + right) / 2).ToString())
If left >= right - 1 Then
If x = arr(left) Then
Return left
ElseIf x = arr(right) Then
Return right
Else
Return -1
End If
return -1
End If

If x = arr(center) Then
Return center
ElseIf x > arr(center) Then
Return SubFind(x,center,right)
ElseIf x < arr(center) Then
Return SubFind(x,left,center)
End If
End Function

End Class
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!