Simple BinarySearch Demo

This demo illustrates using the Array.BinarySearch method to determine whether or not an element exists in a sorted array.


The array of elements is given as:

The array of elements sorted is given as:

Search for a Word


Source Code

<%@ Import Namespace="System.Drawing" %>
<script runat="server" language="VB">
  Dim myArray as String()

  Sub Page_Load(sender as Object, e as EventArgs)
    'Create an array of strings
    Dim saying as String = "There are few girls in Rolla, Missouri."
    
    Dim re as New Regex(" ")
    myArray = re.Split(saying)

    Dim i as Integer
    ltlArrayPresort.Text = "<p><ul>"
    For i = 0 to myArray.Length - 1
      ltlArrayPresort.Text &= "myArray[" & i & "] = " & myArray(i) & "<br />"
    Next i
    ltlArrayPresort.Text &= "</ul></p>"
    
    'Sort the array
    Array.Sort(myArray)
    ltlArraySort.Text = "<p><ul>"
    For i = 0 to myArray.Length - 1
      ltlArraySort.Text &= "myArray[" & i & "] = " & myArray(i) & "<br />"
    Next i
    ltlArraySort.Text &= "</ul></p>"
    
  End Sub


  Sub searchArray(sender as Object, e as EventArgs)
	Dim location as Integer
	location = Array.BinarySearch(myArray, txtSearchTerm.Text)
	
	If location < 0 then
	  lblResults.Text = "The value " & txtSearchTerm.Text & " was not found in the array."
	  lblResults.ForeColor = Color.Red
	Else
	  lblResults.Text = "The value " & txtSearchTerm.Text & " was found at position " & location & "."
	  lblResults.ForeColor = Color.Black
	End If
  End Sub  
</script>

<form runat="server">
  The array of elements is given as: <asp:literal id="ltlArrayPresort" runat="server" /><p>
  The array of elements sorted is given as:
  <asp:literal id="ltlArraySort" runat="server" /><p>
  
  <b>Search for a Word</b><br />
  <asp:textbox id="txtSearchTerm" runat="server" Columns="8" /><br />
  <asp:Button runat="server" Text="Search Array Using BinarySearch"
	OnClick="searchArray" />
	
  <p>
  <asp:label runat="server" id="lblResults" />  
</form>


[Return to the article]