You are here:   HomeJava ProgrammingJava ArraySum and Average the elements of an array for Java Example

# Linear Search in Java Example

by Dinesh Thakur Category: array

Algorithm for Linear Search:

step 2: create an integer array a[] of size arr_size

step 3: initialize i=0

step 4: repeat through step-6 while (i < arr_size)

step 6: i=i+ 1

step 7: initialize i=0

step 8: repeat through step-13 while (i < arr_size)

step 9: initialize j=i+ 1

step 10: repeat through step-12 while (j < arr_size)

step 11: if ( a[i) > a[j]) then interchange a[i] with a[j]

step 12: j=j+ 1

step 13: i=i+ 1

step 14: Reset i=0

step 15: repeat through step-17while (i < arr_size)

step 16: print a[i]

step 17: i=i+ 1

step 19: reset i=0

step 20: repeat through step-22 while (i < arr_size)

step 21: if (value==a[i]) then print i

step 22: i=i+ 1

step 23: Exit

Here is the Java Example for Linear Search:

```import java.util.Scanner;

public class LeanerSearch

{

public static void main(String args[])

{

int i,j,x,arr_size,t;

Scanner s1=new Scanner(System.in);

System.out.print("Enter the size of Array : ");

arr_size =s1.nextInt();

int a[]=new int[arr_size];

System.out.println("\nEnter the Elements of Array");

for(i=0;i<arr_size;i++)

{

a[i]=s1.nextInt();

}

for(i=0;i< arr_size;i++)

{

System.out.print(a[i]+"\t");

}

System.out.print("\n");

for(i=0;i< arr_size;i++)

{

for(j=i+1;j<arr_size;j++)

{

if(a[i]>a[j])

{

t=a[i];

a[i]=a[j];

a[j]=t;

}

}

}

System.out.println("\nSorted Elements of Array is :->\n");

for(i=0;i< arr_size;i++)

{

System.out.print(a[i]+"\t");

}

System.out.print("\nEnter the Value to be Searched : ->");

x=s1.nextInt();

for(i=0;i<arr_size;i++)

{

if(x==a[i])

System.out.println(x+" is Located at Location -> "+(i+1));

}

}

}

```

 Name E-mail

Dinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.

What's New and Popular

Popular Article

Search Content

Basic Courses