Linear Search

Linear Search

 
You are provided a collection and need to search the index of a given n number.
 
Linear Search is a simple approach :
 

  1.  Start from left to right and scan each element until you get the given number.

 
Since, we are going to scan each element then running time complexity of this algorithm would be O(n).
 
However, Linear Search is bad since we are having better approaches like binary search and hashing techniques for faster computation.
 
Let’s see the code.
 



package com.diaryreaders.datastructures.searching;
public class LinearSearch {
public static void main(String[] args) {
int[] array = { 1, 3, 2, 4, 5, 6, 10, 8 };
int index = searchLinear(array, 8);
System.out.println(index);
}
private static int searchLinear(int[] array, int n) {
for (int j = 0; j < array.length; j++) {
if (n == array[j]) {
return j;
}
}
return -1;
}
}


 
Output:

 

 

No Comments Yet

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON