JavaScript Lesson 26: Performing Linear Search

<Lesson 25> [Contents] <Lesson 27>

26.1 Introduction to Linear Search in JavaScript

The ability to perform a search is one of the key functions of any programming languages. We don’t have to look very fast, 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. off 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.

26.2 Performing Linear Search

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:

<title>Performing Linear Search of an Array</title><script type = "text/javascript">
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);
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;
// -->


<h1>Perfoming Linear Search</h1>
<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>

Click Example 26.1 to view the actual output.

<Lesson 25> [Contents] <Lesson 27>

Comments are closed.