Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Linear search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Distinguish|Line search}}{{short description|Sequentially looking in an array}} {{one source|date=November 2010}} {{Infobox algorithm |name={{PAGENAMEBASE}}|class=[[Search algorithm]] |time=[[big O notation#Orders of common functions|''O''(''n'')]] |space = [[big O notation#Orders of common functions|''O''(1)]] iterative |best-time=[[big O notation#Orders of common functions|''O''(1)]] |average-time=[[big O notation#Orders of common functions|''O''(''n'')]] |optimal=Yes |data= }} In [[computer science]], '''linear search''' or '''sequential search''' is a method for finding an element within a [[list (computing)|list]]. It sequentially checks each element of the list until a match is found or the whole list has been searched.{{Sfn|Knuth|1998|loc=Β§6.1 ("Sequential search")}} A linear search runs in [[Time complexity#Linear time|linear time]] in the [[Best, worst and average case|worst case]], and makes at most {{math|''n''}} comparisons, where {{math|''n''}} is the length of the list. If each element is equally likely to be searched, then linear search has an average case of {{math|{{Sfrac|''n+1''|2}}}} comparisons, but the average case can be affected if the search probabilities for each element vary. Linear search is rarely practical because other [[search algorithm]]s and schemes, such as the [[binary search algorithm]] and [[hash table]]s, allow significantly faster searching for all but short lists.{{Sfn|Knuth|1998|loc=Β§6.2 ("Searching by Comparison Of Keys")}} ==Algorithm== A linear search sequentially checks each element of the list until it finds an element that matches the target value. If the [[algorithm]] reaches the end of the list, the search terminates unsuccessfully.{{Sfn|Knuth|1998|loc=Β§6.1 ("Sequential search")}} ===Basic algorithm=== Given a list {{math|''L''}} of {{math|''n''}} elements with values or [[Record (computer science)|records]] {{math|''L''<sub>0</sub> .... ''L''<sub>''n''β1</sub>}}, and target value {{math|''T''}}, the following [[subroutine]] uses linear search to find the index of the target {{math|''T''}} in {{math|''L''}}.{{Sfn|Knuth|1998|loc=Β§6.1 ("Sequential search"), subsection "Algorithm B"}} # Set {{math|''i''}} to 0. # If {{math|''L''<sub>''i''</sub> {{=}} ''T''}}, the search terminates successfully; return {{math|''i''}}. # Increase {{math|''i''}} by 1. # If {{math|''i'' < ''n''}}, go to step 2. Otherwise, the search terminates unsuccessfully. ===With a sentinel=== The basic algorithm above makes two comparisons per iteration: one to check if {{math|''L''<sub>''i''</sub>}} equals ''T'', and the other to check if {{math|''i''}} still points to a valid index of the list. By adding an extra record {{math|''L''<sub>''n''</sub>}} to the list (a [[sentinel value]]) that equals the target, the second comparison can be eliminated until the end of the search, making the algorithm faster. The search will reach the sentinel if the target is not contained within the list.{{Sfn|Knuth|1998|loc=Β§6.1 ("Sequential search"), subsection "Algorithm Q"}} # Set {{math|''i''}} to 0. # If {{math|''L''<sub>''i''</sub> {{=}} ''T''}}, go to step 4. # Increase {{math|''i''}} by 1 and go to step 2. # If {{math|''i'' < ''n''}}, the search terminates successfully; return {{math|''i''}}. Else, the search terminates unsuccessfully. ===In an ordered table=== If the list is ordered such that {{math|''L''<sub>0</sub> ≤ ''L''<sub>1</sub> ... ≤ ''L''<sub>''n''β1</sub>}}, the search can establish the absence of the target more quickly by concluding the search once {{math|''L''<sub>''i''</sub>}} exceeds the target. This variation requires a sentinel that is greater than the target.{{Sfn|Knuth|1998|loc=Β§6.1 ("Sequential search"), subsection "Algorithm T"}} # Set {{math|''i''}} to 0. # If {{math|''L''<sub>''i''</sub> ≥ ''T''}}, go to step 4. # Increase {{math|''i''}} by 1 and go to step 2. # If {{math|''L''<sub>''i''</sub> {{=}} ''T''}}, the search terminates successfully; return {{math|''i''}}. Else, the search terminates unsuccessfully. ==Analysis== For a list with ''n'' items, the best case is when the value is equal to the first element of the list, in which case only one comparison is needed. The worst case is when the value is not in the list (or occurs only once at the end of the list), in which case ''n'' comparisons are needed. If the value being sought occurs ''k'' times in the list, and all orderings of the list are equally likely, the expected number of comparisons is :<math> \begin{cases} n & \mbox{if } k = 0 \\[5pt] \displaystyle\frac{n + 1}{k + 1} & \mbox{if } 1 \le k \le n. \end{cases} </math> For example, if the value being sought occurs once in the list, and all orderings of the list are equally likely, the expected number of comparisons is <math>\frac{n + 1}2</math>. However, if it is ''known'' that it occurs once, then at most ''n'' - 1 comparisons are needed, and the expected number of comparisons is :<math>\displaystyle\frac{(n + 2)(n-1)}{2n}</math> (for example, for ''n'' = 2 this is 1, corresponding to a single if-then-else construct). Either way, [[asymptotic complexity|asymptotically]] the worst-case cost and the expected cost of linear search are both [[big O notation|O]](''n''). ===Non-uniform probabilities=== The performance of linear search improves if the desired value is more likely to be near the beginning of the list than to its end. Therefore, if some values are much more likely to be searched than others, it is desirable to place them at the beginning of the list. In particular, when the list items are arranged in order of decreasing probability, and these probabilities are [[geometric distribution|geometrically distributed]], the cost of linear search is only O(1). <ref name="knuth"> {{cite book | first=Donald |last=Knuth |author-link=Donald Knuth | series = The Art of Computer Programming | volume = 3 |title=Sorting and Searching | edition = 3rd | publisher = Addison-Wesley | year = 1997 | isbn = 0-201-89685-0 | chapter = Section 6.1: Sequential Searching | pages = 396β408 }} </ref> ==Application== Linear search is usually very simple to implement, and is practical when the list has only a few elements, or when performing a single search in an un-ordered list. When many values have to be searched in the same list, it often pays to pre-process the list in order to use a faster method. For example, one may [[sort (computing)|sort]] the list and use [[Binary search algorithm|binary search]], or build an efficient [[search data structure]] from it. Should the content of the list change frequently, repeated re-organization may be more trouble than it is worth. As a result, even though in theory other search algorithms may be faster than linear search (for instance [[binary search]]), in practice even on medium-sized arrays (around 100 items or less) it might be infeasible to use anything else. On larger arrays, it only makes sense to use other, faster search methods if the data is large enough, because the initial time to prepare (sort) the data is comparable to many linear searches.<ref name=":0">{{Cite web |first=Adam |last=Horvath |url=http://blog.teamleadnet.com/2012/02/quicksort-binary-search-and-linear.html |title=Binary search and linear search performance on the .NET and Mono platform |access-date=19 April 2013 }}</ref> ==See also== * [[Ternary search]] * [[Hash table]] * [[Linear search problem]] ==References== ===Citations=== {{Reflist}} ===Works=== {{Sfn whitelist |CITEREFKnuth1998}} * {{TAOCP|volume=3|edition=2}} {{ISBN|0-201-89685-0}} {{DEFAULTSORT:Linear Search}} [[Category:Search algorithms]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite book
(
edit
)
Template:Cite web
(
edit
)
Template:Distinguish
(
edit
)
Template:ISBN
(
edit
)
Template:Infobox algorithm
(
edit
)
Template:Math
(
edit
)
Template:One source
(
edit
)
Template:Reflist
(
edit
)
Template:Sfn
(
edit
)
Template:Sfn whitelist
(
edit
)
Template:Short description
(
edit
)
Template:TAOCP
(
edit
)