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.w3schools; 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 |