The ability to perform a search is one of the key functions of any programming languages. We don't have to look very far, just take a look at Google, the most popular search engine in the world. Due to its exclusive and highly effective search algorithm, it commands a major portion of the search engine market, and hence the search advertising market. In fact, it captured more than 60% of the Internet advertising market!
JavaScript is an effective scripting language that can be used to perform search operations on the web. Of course, it has to work with server-side programming languages such as Java and CGI to be effective. However, you will learn simple search algorithm here using JavaScript.
In this lesson, we will learn how to write a script to perform a linear search for an array that consists of integers. We employ the If operator to compare the search value entered by the user and each number in the array. If the search value is equal to the number concern, it will return the position of that number in the array (which is actually the value of the subscript plus 1, as the subscript of the array starts with 0). we need to use the function parseInt to convert the value of the subscript into a numeric value so that it can perform arithmetic operation. We also use the logical operators for and if to perform the search operation.
The following is the script:
<script> var a = [4,8,13,17,19,22,25,35,39,41,49,53,59,67,69,75,78,83,90,99] function SearchArray() { var searchNum = searchForm.inputVal.value; var position = Search( a, parseInt( searchNum ) ); if ( position != -1 ) searchForm.result.value ="The number is in position " +( parseInt(position)+1); else searchForm.result.value = "The number is not found"; } // Search "theArray" for the specified "key" value function Search( theArray, key ) { for ( var n = 0; n < theArray.length; ++n ) if ( theArray[ n ] == key ) return n; return -1; } </script>You also need to create the following search form and button
<form name = "searchForm" action = ""> <p>Enter an Integer between 0 and 100 (excluding 0 and 100)<br /> <input name = "inputVal" type = "text" /> <input name = "search" type = "button" value = "Search" onclick = "SearchArray()" /><br /></p> <p>Result<br /> <input name = "result" type = "text" size = "30" /></p> </form> </body> </html>
Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy