Linear Search Implementation Using JavaScript

Posted By : Rajan Rawat | 18-Sep-2017

What is Linear Search?

Today the programmers are working on large amount of data stored on arrays. It should be compulsary to determine an array which contains a value which matches a certain key value. When it comes to searching a particular element value in array that is called as searching. So for searching an element in array we have a liner search technique.

Linear search tehnique is based on collection of items. Linear search technique relies omn traversing a list from strating to end tha will explore the properties of all the elements which needs to be found on the way.

 

 

For example:- 

Let's take an array of itergers with the size n. We have to find he positions and print the positions of all elements with value of x. Linear search technique is based on the idea of matching each elements from  strating of the list to end of the list with the integer x, and then we will print the positions of elements if we have condition is true

 

 

Implementation

 

Code for example is as follow

                for(start to end of array)
                  {
               if (current element equals to 5)  
                   {
                     print (current index);
                  }
                }

 

Let's take the following image for example

In the above pic if you want to find the position of occurence of number 8 in this array. To find the position, every in this array from start to end be compared with number 8, to check and find that which element mathces in number 8

Now lets see example of Implementaion of linear search using javascript

<html>
<head>
<title>linear</title>
<script type="text/javascript">
    function linear()
{
    var n=parseInt(prompt("Enter the size of an array"));
    var a=new Array(n);
    var t=0;
    for(var i=0; i<a.length; i++)
    {
        a[i]=parseInt(prompt("Enter array elements"));
    }
    var k=parseInt(prompt("Enter the key element to search: "));
    for(var i=0; i<a.length; i++)
    {
        if(k==a[i])
        {
            t=1;
            break;
        }
    }
    if(t==1)
    {
        document.writeln("Element "+a[i]+ " Found at Position:"+i);
    }
    else
    {
        document.writeln("Element Not Found");
    }
}
</script>
</head>
<body  onLoad="linear()"></body>
</html>

 

 

OUTPUT

About Author

Author Image
Rajan Rawat

Rajan is a UI Developer, having good knowledge of HTML, CSS and javascript. His hobbies are internet surfing and watching sports.

Request for Proposal

Name is required

Comment is required

Sending message..