Anda di halaman 1dari 5

<html> <head> <script type="text/javascript"> var a=new Array( 15 ); for ( var i=0;i<a.length;++i ) a[ i ]=2*i; function buttonPressed( ) { var result=binary.result.

value; var searchKey=binary.inputVal.value; binary.result.value="Portions of array searched\n" var element=binarySearch(a,parseInt(searchKey)); if (element!=-1) binary.result.value+="\nFound value in element"+" "+(element+1); else binary.result.value+="\nValue not found"; } function binarySearch(theArray,key) { var low=0; var high=theArray.length-1; var middle; while(low<=high) { middle=(low+high)/2; buildOutput(theArray,low,middle,high); if (key==theArray[middle]) return middle;

else if (key<theArray[middle]) high=middle-1; else low=middle+1; } return-1; } function buildOutput(theArray,low,middle,high) { for (var i=0;i<theArray.length;i++) { if(i<low||i>high) binary.result.value+=" "; else if(i==middle) binary.result.value+=theArray[i]+(theArray[i]<10?"*":"*"); else binary.result.value+=theArray[i]+(theArray[i]<10?"":""); } binary.result.value+="\n"; } </script> </head> <body> <form name="binary"> <p>Enter integer search key<br/> <input name="inputVal" type="text"/> <input type="button" value="search" onClick="buttonPressed()"/><br/></p> <p>Result<br/>

<textarea name="result" rows="7" cols="60"> </textarea> </p> </form> </body> </html>

<html> <head> <script type="text/javascript"> function a() { var target,i,a=new Array("2","4","6","8","10","12","14","16","18","20"); target=parseInt(search.text1.value); for(i=1;i<10;i++) { if (target==a[i]) search.text2.value="your target is found as"+ i +"element" } } </script> </head> <body>

<form method="get" id="search"> <label>enter the element to be searched</label><br/> <input type="text" id="text1"> <input type="button" onClick="a()" value="search"><br/> result <br/> <input type="text" id="text2" size="80"> <br/> </form> </body> </html>

Anda mungkin juga menyukai