Home | Tutorials | Articles | Videos | Products | Tools | Search
 Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact
 Data Structures > Search > Linear Search

# Linear Search

Linear search is a straightforward searching algorithm. In this we iterate through all the elements of array sequentially to find the matching element. The elements of array can be in any order. Its time complexity is O(n) read as Order of n.

• Average case time complexity of Linear search is O(n/2)
• Worst case time complexity of Linear search is O(n)

 File Name  : com/bethecoder/tutorials/ds/search/LinearSearch.java Author  : Sudhakar KV Email  : [email protected]

 package com.bethecoder.tutorials.ds.search; import java.util.Arrays; public class LinearSearch {   /**    * @param args    */   public static void main(String[] args) {     int[] list = { 6, 5, 1, 8, 3, 9, 4, 0, 2, 7 };     System.out.println("Array : " + Arrays.toString(list));     //Linear Search     linearSearch(list, 2);     linearSearch(list, 8);     linearSearch(list, 12);   }   /**    * Returns a positive index if the search element is    * available in the given array otherwise returns -1.    *     * @param list    * @param searchEle    * @return    */   public static int linearSearch(int[] list, int searchEle) {     int index = -1;     for (int i = 0 ; i < list.length ; i ++) {       if (list[i] == searchEle) {         index = i;          break;       }     }          System.out.println(searchEle + " found in array at index : " + index);     return index;   } }

It gives the following output,
Array : [6, 5, 1, 8, 3, 9, 4, 0, 2, 7]
2 found in array at index : 8
8 found in array at index : 3
12 found in array at index : -1