Search This Blog

Thursday 21 August 2014

5. HTML and JSP Program to Sort Names and Search for a Key using Recursive Binary Search.

Filename:Bin5.html
<!-- 5. HTML program to sort and search using recursive binary search. -->
<HTML>
    <HEAD>
        <TITLE>Sorting and Recursive Binary Searching</TITLE>
    </HEAD>

    <BODY>
        <H1>Program to search for key</H1>
        <FORM ACTION="Bin5.jsp" METHOD="POST">
              Please enter the search key:
            <BR>
           
              <input type="text" NAME="text1" >
            <BR>
            <INPUT TYPE="SUBMIT"  VALUE="Submit">
        </FORM>
    </BODY>
<HTML>


Filename:Bin5.jsp
<!-- 5. JSP Pro search for a key using recursive binary searchgram to sort strings and -->
<html>
  <body>
     <%
       final  String a[]={"Pineapple" , "Orange" , "Apple",

       "Grapes", "Banana","Mango"};
       String  temp;
       int flag=0,j,index;
       out.println("The sorted list of names:");
       for(j=0; j<a.length;j++)
       {
          for (int i=j+1 ; i<a.length; i++)
          {
             if(a[i].compareToIgnoreCase(a[j]) < 0)
             {
                temp= a[j];
                a[j]= a[i];
                a[i]=temp;
             }
          }
        %>
        <br>
        <%
        out.print(a[j]);
    }
 %>
 <br>
 <br>
   <%
    String key=request.getParameter("text1");
    index = binsearch(key,a,0,a.length);
    if(index > -1)
        out.println("Search Key Found at location "+(index+1));
    else
        out.println("Search Key Not Found!");
   %>
   <%!
       public static int binsearch(String key, String[] a, int low, int high)
       {
            if (high <= low)
                return -1;
            int mid = low + (high - low) / 2;
            int cmp = a[mid].compareToIgnoreCase(key);
            if (cmp > 0)
                  return binsearch(key, a, low, mid);
            else if(cmp < 0)
                return binsearch(key, a, mid+1, high);
            else 
                 return mid;
        }
   %>
  <body>
</html>

1 comment :

FREE Hit Counters