Linear Search Algorithm in Java

(213 Views)


Search algorithms are useful in many areas. One such search algorithm is Linear search. In this piece, you are going to get the complete details about Linear search algorithm in Java.

Linear Search in Java

There are mainly two types of search algorithms including those that don’t make any assumption regarding the order of the list and another one that assumes the list is ordered. Linear search is the simplest search algorithm among them.

What is Linear Search Algorithm?

Linear search is implemented when you want to find an element in a list. It performs a sequential search on each element of a list till a match is not found or the search of the entire list is done. The return value is considered as the index at which the search term was found or indicator when the search term was not found.

Performance of Linear Search

  • Best case: When the search terms are in the first slot of the array then the base case occurs. The number of comparisons, in this case, is 1.
  • Worst case: It occurs when the search term will be in the last slot of the array, or not available. The number of comparisons, in this case, will be equal to the array size. If an array has N items, then it takes N comparisons in this case.
  • Average case: The search term exists in the middle of the array. The number of comparisons, in this case, is N/2.
  • If you have looked closely, then you will find that the number of comparisons is proportional to the number of items in the array, N in both the worst and average case, the. Therefore, we can say that the number of comparisons is order N in both or O(N) for short. For the best case, the number of comparisons is order 1, or O(1) in short.

Algorithm

  • Get the array length
  • Choose the element you want to perform search and store it in the variable value
  • Make comparison between each element and variable value
  • When it match, print a message saying element has been found
  • If not, print a message that element not found.
public class LinearSearch { public static void main(String args[]){ int array[] = {10, 20, 25, 63, 96, 57}; int size = array.length; int value = 25; for (int i=0 ;i< size-1; i++){ if(array[i]==value){ System.out.println("Element found index is :"+ i); }else{ System.out.println("Element not found"); } } } }

Output

Element found index is: 2

So, isn’t it is easy to use the Linear search algorithm. Anyone can learn it with some practice if he knows to program in any language.

Solution Worked 0 UpvotesUpvote

        

Solution Didn't Worked 0 DownvotesDownvote



Comments



Get Programming Help
Search

Play 2048 Game Online


Search Tags

    Linear Search Pseudocode

    Java Program for Linear Search Algorithm