Binary Search Algorithm For BCA

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

// To search a number using Binary Search

Public Class Form1


Dim i, n,no, a(10) As Integer

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click
Static i As Integer
no = Val(TextBox1.Text)
TextBox1.Focus()

If (i < no) Then


a(i) = Val(TextBox2.Text)
ListBox1.Items.Add(a(i))
i = i + 1

End If
If (i >= no) Then
MsgBox("array full")

End If

TextBox2.Clear()
TextBox2.Focus()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Dim lb, ub, mid, no, x As Integer
x = 0
no = Val(TextBox1.Text)
n = Val(TextBox3.Text)

lb = 0
ub = no - 1
While (lb <= ub)
mid = (lb + ub) \ 2
If (a(mid) = n) Then
MsgBox(" Number is present in the list")
x = x + 1
Exit While

End If

If (n > a(mid)) Then

lb = mid + 1
End If

If (n < a(mid)) Then

ub = mid - 1
End If

End While

If (x = 0) Then
MsgBox(" Number is not present in the list")
End If

End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button3.Click
Me.Close()

End Sub

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button4.Click
TextBox1.Clear()
TextBox2.Clear()
ListBox1.Items.Clear()

End Sub

End Class

You might also like