Linear Search

In computer science, linear search is a search algorithm, also known as sequential search, that is suitable for searching a set of data for a particular value. It operates by checking every element of a list until a match is found. Linear search runs in O(N). If the data are distributed randomly, on average N/2 comparisons will be needed. The best case is that the value is equal to the first element tested, in which case only 1 comparison is needed. The worst case is that the value is not in the list, in which case N comparisons are needed. Here is a sample implementation in Ruby:
 def linear_search(array, value) 
     for element in array         return true if element == value     end     return false 
end
Here is a sample implementation in PHP:
 function linear_search($array, $value) { 
     foreach ($array as $current) {         if ($current == $value) {             return TRUE;         }     }     return FALSE; 
}
Here is another example in Java:
 public static boolean linear_search(Comparable array, Comparable value) { 
      for(Comparable c : array) {          if(c.compareTo(value) == 0)               return true;      } 
      return false; 
}
And here is a sample implementation in C++ using templates and STL containers:
 template  bool linear_search(const C& array, const T& value) { 
     C::const_iterator iter = array.begin();     C::const_iterator end = array.end();     while (iter != end) {         if (*iter == value)             return true;         ++iter;     }     return false; 
}
Linear search can be used to search an unordered list. The more efficient binary search can only be used to search an ordered list. If more than a small number of searches are needed, it is advisable to use a more efficient data structure. One approach is to sort and then use binary searches. Another common one is to build up a hash table and then do hash lookups.

 

<< PreviousWord BrowserNext >>
los angeles international airport
la tne culture
lorenz curve
literate programming
logistic map
levant
league of nations mandate
loudon classic
lincoln, new hampshire
laser applications
lorenz attractor
left arm orthodox spin
late helladic
laser construction
logical conjunction
logical operator
propositional calculus
lazy evaluation
lemuridae
lucent technologies
lupercalia
list of atheists
list of buddhists
list of agnostics
linked list
logic gate
landmine
libertarian party
loa
labour economics
lammas
longmeadow, massachusetts
left and right
lizard
list of deists
list of hindus
leviticus
l. frank baum
lake ladoga
language families and languages
looe island
latex
list of saints
lebesgue measure