c# - How to perform binary search on an array

Array binary search
array-binary-search.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>
<%@ Import Namespace="System.IO" %>
    
<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)    
    {  
        string[] colors = new string[]  
        {  
            "white",  
            "green",  
            "yellow",  
            "blue",  
            "pink",  
        };

        Label1.Text = "colors array.........<br />";
        foreach (string s in colors)
        {
            Label1.Text += s + "<br />";
        }
       
        //binary search work correctly only on a pre sorted array.
        Array.Sort(colors);
       
        Label1.Text += "<br />sorted colors array.........<br />";
        foreach (string s in colors)  
        {  
            Label1.Text += s + "<br />";  
        }

        int index = Array.BinarySearch(colors, "pink");
        Label1.Text += "<br />index of color [pink] by binary search = " + index.ToString();
    }    
</script>    
    
<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - array binary search</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:DarkBlue; font-style:italic;">    
            c# example - array binary search
        </h2>    
        <hr width="550" align="left" color="LightBlue" />      
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"    
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="test array binary search"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>
More c# examples