CodesJava

Easy learning with example program codes

Java linear search program


Search algorithm

Search algorithm refers to a step-by-step procedure which is used to locate specific data among a collection of data. All search algorithms use a search key in order to proceed for the search operation. The efficiency of a search algorithm is measured by the number of times a comparison of the search key is done in the worst case. The notation used in search algorithms is O(n), where n is the number of comparisons done.

Linear search

Linear search is a way of finding a target value within a collection of data. It is also known as sequential search. It sequentially checks each element of the collection data for the target value until a match is found or until all the elements have been searched.

Basic algorithm

Given a collection of data L of n elements with values or records L0 … Ln−1, and target value T, the following subroutine uses linear search to find the index of the target T in L.

  • Set i to 0.
  • If Li = T, the search terminates successfully; return i.
  • Increase i by 1.
  • If i < n, go to step 2. Otherwise, the search terminates unsuccessfully.

Note: Linear search is not used commonly because it is slower than binary search and hashing.

Example

package com.codesjava;
 
public class Test {
    public static int linearSearch(int[] data, int key){    
        for(int i=0;i<data.length;i++){    
            if(data[i] == key){    
                return i;    
            }    
        }    
        return -1;    
    }    
 
    public static void main(String args[]){
	int[] data= {50,27,30,50,70,9,19};    
        int key = 9;    
        System.out.println(key+" is found at index: "+linearSearch(data, key));  
   }
}

Output

9 is found at index: 5


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap