RokiAdhytama

Linear Search - Chapter 11

Jul 3rd, 2022
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. <html xmlns = "http://www.w3.org/1999/xhtml">
  2. <head>
  3. <title>Linear Search of an Array</title>
  4.  
  5. <script type = "text/javascript">
  6. <!--
  7. var a = new Array( 100 ); // create an Array
  8.  
  9. // fill Array with even integer values from 0 to 198
  10. for ( var i = 0; i < a.length; ++i )
  11. a[ i ] = 2 * i;
  12.  
  13. // function called when "Search" button is pressed
  14. function buttonPressed()
  15. {
  16. var searchKey = searchForm.inputVal.value;
  17.  
  18. // Array a is passed to linearSearch even though it
  19. // is a global variable. Normally an array will
  20. // be passed to a method for searching.
  21. var element = linearSearch( a, parseInt( searchKey ) );
  22.  
  23. if ( element != -1 )
  24. searchForm.result.value =
  25. "Found value in element " + element;
  26. else
  27. searchForm.result.value = "Value not found";
  28. }
  29.  
  30. // Search "theArray" for the specified "key" value
  31. function linearSearch( theArray, key )
  32. {
  33. for ( var n = 0; n < theArray.length; ++n )
  34. if ( theArray[ n ] == key )
  35. return n;
  36.  
  37. return -1;
  38. }
  39. // -->
  40. </script>
  41.  
  42. </head>
  43.  
  44. <body>
  45. <form name = "searchForm" action = "">
  46. <p>Enter integer search key<br />
  47. <input name = "inputVal" type = "text" />
  48. <input name = "search" type = "button" value = "Search"
  49. onclick = "buttonPressed()" /><br /></p>
  50.  
  51. <p>Result<br />
  52. <input name = "result" type = "text" size = "30" /></p>
  53. </form>
  54. </body>
  55. </html>
Advertisement
Add Comment
Please, Sign In to add comment