You are on page 1of 2

Program 2 : Binary Search Application

Imports System.Console
Module Module1

Sub accpet(ByRef a() As Integer)


Dim i As Integer

For i = 1 To a.Length - 1
a(i) = Val(ReadLine())
Next i

End Sub

Sub sort(ByRef a() As Integer)

Dim i, j, n, temp As Integer

n = a.Length

For i = 1 To n - 1
For j = i To n - 1

If a(i) > a(j) Then


temp = a(i)
a(i) = a(j)
a(j) = temp
End If

Next
Next

End Sub

Sub display(ByRef a() As Integer)

For i As Integer = 1 To a.Length - 1


WriteLine(a(i))
Next
End Sub

Function bsearch(ByRef a() As Integer, ByVal key As Integer) As


Integer

Dim low As Integer = 0


Dim high, mid As Integer

high = a.Length - 1

While low <= high


mid = (low + high) / 2

If a(mid) = key Then


Return mid
ElseIf a(mid) > key Then
high = mid - 1

Else
low = mid + 1
End If

End While
Return -1
End Function
Sub Main()

Dim a(), n, key, loc As Integer

WriteLine("Enter no of elements")

n = ReadLine()
ReDim a(n)

WriteLine("Enter elements into array")


accpet(a)
sort(a)
WriteLine("Given elements are")
display(a)

WriteLine("Enter element to search")


key = Val(ReadLine)

loc = bsearch(a, key)

If loc = -1 Then
WriteLine("element not found")
Else
WriteLine("element found at" & loc)

End If

Read()
End Sub

End Module

You might also like