[go: up one dir, main page]

0% found this document useful (0 votes)
11 views2 pages

Binary Search

Uploaded by

msufwans
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Binary Search

Uploaded by

msufwans
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Module Module1

Sub Main()
Const ARRAY_SIZE As Integer = 8

Dim array(ARRAY_SIZE) As Integer


Console.WriteLine("Enter {0} numbers to be sorted ", ARRAY_SIZE)
For index = 1 To ARRAY_SIZE
Try
array(index) = Console.ReadLine()
Catch ex As Exception
Console.WriteLine(ex.Message)
index = index - 1
End Try
Next

' Insertion Sort method

Dim ItemToBeInserted, CurrentItem As Integer

For pointer = 2 To ARRAY_SIZE


ItemToBeInserted = array(pointer)
CurrentItem = pointer - 1
While (ItemToBeInserted < array(CurrentItem) And CurrentItem >= 1)
array(CurrentItem + 1) = array(CurrentItem)
CurrentItem = CurrentItem - 1
End While

array(CurrentItem + 1) = ItemToBeInserted
Next

Console.WriteLine("The sorted array is")

For i = 1 To ARRAY_SIZE
Console.WriteLine("{0} element is {1}", i, array(i))
Next

' Binary Search


Dim SearchItem As String
Console.WriteLine("Please Enter the number you want to find from the array")
SearchItem = Console.ReadLine()

Dim Found, SearchFailed As Boolean


Dim First, Middle, Last As Integer

Found = False
SearchFailed = False
First = 1
Last = ARRAY_SIZE

While Not Found And Not SearchFailed


Middle = (First + Last) / 2
If array(Middle) = SearchItem Then
Found = True
Else
If First >= Last Then
SearchFailed = True
Else
If array(Middle) > SearchItem Then
' Must be in the first half
Last = Middle - 1
Else
' Must be in the second half
First = Middle + 1
End If
End If
End If
End While

If Found = True Then


Console.WriteLine("The position of the item is {0}", Middle)
Else
Console.WriteLine("Item is not present in the array")
End If

Console.ReadKey()
End Sub

End Module

You might also like