Linear Search in Java


Introduction

In this article we are going to discuss or describe Java linear searches. This is the simplest method of searching. In this method, the element to be searched is sequentially searched in the list. This method can be applied to a sorted or an unsorted list.

Linear Search (Sequential Search)

A sequential search of a list/array begins at the beginning of the list/array and continues until the item is found or the entire list/array has been searched. A linear search (aka Sequential Search) is the most fundamental and important of all algorithms. It is simple to understand and implement.

The following figure specifies how a linear search actually works.

linear-search.gif

Algorithms 

Step 1: Take a search element into key elements and start the search in the list.

System.out.print("\nEnter Search Key : ");

System.out.flush();

try

{

BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));

str=obj.readLine();

key=Integer.parseInt(str);

Step 2: Match this key element to the starting of the array or list and increase one by one.

 for(int i=0;i<size;i++
{

 if(seaArr[i]==key)

  return(i+1);
}

Step 3 : When the key element matches the array or list index's element then return the index number.

Step 4 : If the increment reaches the end of the link or array and a match was not found then return a message such as "Not found".

Example

import java.io.*;

class search

{

String str;

int key,size,seaArr[];

public void getdata()

{

System.out.print("Enter how many data you want to enter : ");

System.out.flush();

try

{

BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));

str=obj.readLine();

size=Integer.parseInt(str);

seaArr=new int[size];

for(int i=0;i<size;i++)

{

System.out.print("Enter element at "+(i+1)+"th position  :  ");

System.out.flush();

str=obj.readLine();

seaArr[i]=Integer.parseInt(str);

}

}

catch(Exception e)  

{

System.out.println(e);

}

}

public int LinSrch()

{

System.out.println("=====LINEAR SEARCH=====\n");

getdata();

System.out.print("\nEnter Search Key : ");

System.out.flush();

try

{

BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));

str=obj.readLine();

key=Integer.parseInt(str);

for(int i=0;i<size;i++)

{

if(seaArr[i]==key)

return(i+1);

}

}

catch(Exception e)

{

System.out.println(e);

}

return(0);

}   

}

class  Linear

{

public static void main(String args[])

{

search o1 = new search();

int result;

result=o1.LinSrch();

if(result==0)

System.out.println("\nSearch Not Found");

else

System.out.println("\nSearch is Located at "+result+" Position");

}

}

Output

linearcmd.jpg

Resources

How Count Sort works
Sorting, Searching and some other useful programs
Use of ByteStreams and CharacterStreams in JAVA
Learning JDBC (Java Database Connectivity)
Working with Hibernate - Display , Insert, Update and Delete in JAVA
 

Up Next
    Ebook Download
    View all
    Learn
    View all