Wednesday, January 30, 2013

Linear Search Algorithm

Linear search (aka Sequential Search) is the most fundamental and important of all algorithms. It is simple to understand and implement. This is a very straightforward loop comparing every element in the array with the key. As soon as an equal value is found, it returns. If the loop finishes without finding a match, the search failed and false is returned. Start at the beginning of the list and check every element of the list. Duh. Very slow (order O(n)) but works on an unsorted list.

Here's an implementation of linear search on an array (in Java):
 boolean linearSearch(int[] arr, int target)
  { 
 int i = 0;
 while (i < arr.length) {
   if (arr[i] == target) {
  return true;
   } // if 
   ++i;
 } 
 return false;
  } 
For small arrays, linear search is a good solution because it's so straightforward. In an array of a million elements linear search on average will take 500,000 comparisions to find the key. For a muchfaster search, take a look at binay search.

No comments:

Post a Comment